Android学习之SQLite的基本使用

雨燕双飞 提交于 2020-01-13 20:10:19

本文主要是针对于初学者使用。

AndroidStudio使用版本:

Android Studio 3.5
Build #AI-191.8026.42.35.5791312, built on August 9, 2019
JRE: 1.8.0_202-release-1483-b03 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 7 6.1

Android手机测试版本:Android6.0,华为荣耀6

本博文的实现功能:通过输入Activity,保存输入数据进入SQLite数据库,然后通过宁一个Activity显示出SQLite中的数据信息。

(一)、

在手机上进行数据库的开发,基本步骤主要是以下几步,数据库名:record.db,数据表名:personinfo_record

1、创建数据库:

创建数据库需要继承SQLiteOpenHelper这个抽象类。

本文中使用的方法是普遍使用方法,可以借鉴。如下:

public class DBHelperSub extends SQLiteOpenHelper implements Serializable {

    private String dbName;
    private Context context;
    private SQLiteDatabase.CursorFactory cursorFactory;
    private int version;
    private String tableName;

    private String CREATE_TABLE;

    public DBHelperSub(Context context, String dbName,String tableName,SQLiteDatabase.CursorFactory cursorFactory,int version)
    {
        super(context,dbName,cursorFactory,version);
        this.dbName = dbName;
        this.context = context;
        this.cursorFactory = cursorFactory;
        this.version = version;
        this.tableName = tableName;
//第一次创建未有数据库时的SQL指令语句。
        this.CREATE_TABLE ="create table if not exists personinfo_record (id integer primary key autoincrement not null,"
                +"name text not null,"
                +"sex text not null,"
                +"age integer not null,"
                +"phone text not null,"
                +"girlfriend_name text,"
                +"girlfriend_phone text,"
                +"girlfriend_age integer"
                +")";;

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

//该部分用于执行指令语句,一般是在未有数据库时执行,一旦apk文件创建,就只执行一次
        try {
            sqLiteDatabase.execSQL(CREATE_TABLE);
            Toast.makeText(context, "创建成功", Toast.LENGTH_SHORT).show();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(context, "创建失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
//该部分用于更新数据库使用的函数。
    }
}

2、将需要存储在数据库中的信息插入数据库

一般形式如下:可以直接使用该格式。只是类对象dataBean是自定义的,主要用于保存信息,类似于结构体的功能。可以直接将信息保存进入ContentValues类中,即可以不用自定义类DataBean。

ContentValues values = new ContentValues();
                    values.put("name", dataBean.getName());
                    values.put("sex", dataBean.getSex());
                    values.put("age", dataBean.getAge());
                    values.put("phone", dataBean.getPhoneNumber());
                    values.put("girlfriend_name", dataBean.getGirlfriendName());
                    values.put("girlfriend_phone", dataBean.getGirlFriendTel());
                    values.put("girlfriend_age", dataBean.getGirlFriendAge());



                    SQLiteDatabase sqLiteDatabase = dbHelperSub.getWritableDatabase();

                    sqLiteDatabase.insert("personinfo_record", null, values);

3、显示SQLite中保存的数据

一般形式如下:

 SQLiteDatabase database = getApplication().openOrCreateDatabase("record.db", 0, null);
        if(database.isOpen())
        {

            String sql = "select * from personinfo_record";
            Cursor cursor = database.rawQuery(sql.toString(), null);

            if(cursor !=null)
            {
                cursor.moveToFirst();
                //Toast.makeText(getApplicationContext(),String.valueOf(cursor.getString(cursor.getColumnIndex("name"))), Toast.LENGTH_SHORT).show();
                while (cursor.moveToNext())
                {
                    textView.append(cursor.getString(cursor.getColumnIndex("name")));
                }
                //Toast.makeText(getApplicationContext(), cursor.getString(cursor.getColumnIndex("name")), Toast.LENGTH_SHORT).show();
            }

        }

(二)、

第一步:首先创建输入信息界面:MainActivity

页面布局情况:activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity"
    android:focusable="true"
    android:focusableInTouchMode="true">

    <!--对于姓名输入行-->
    <TextView
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:id="@+id/tv_name"
        android:textColor="#440C0101"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:layout_alignParentStart="true"
        android:layout_marginStart="10dp"
        android:text="@string/tv_name"/>

    <EditText
        android:layout_width="240dp"
        android:layout_height="40dp"
        android:id="@+id/ev_name"
        android:textSize="20sp"
        android:textColor="#0A0101"
        android:layout_marginStart="20dp"
        android:layout_toEndOf="@+id/tv_name"
        android:layout_marginTop="20dp"
        android:hint="@string/ev_name"
        android:imeOptions="actionDone"
        android:singleLine="true"/>

    <!--对于性别输入行-->
    <TextView
        android:id="@+id/tv_sex"
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:layout_below="@+id/tv_name"
        android:layout_alignParentStart="true"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:textColor="#440C0101"
        android:textSize="20sp"
        android:text="@string/tv_sex"/>

    <Spinner
        android:layout_width="240dp"
        android:layout_height="40dp"
        android:id="@+id/sn_sex"
        android:spinnerMode="dropdown"
        android:entries="@array/sex_items"
        android:layout_marginStart="20dp"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/ev_name"
        android:layout_toEndOf="@+id/tv_sex"/>


    <!--对于年龄输入行-->
    <TextView
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:id="@+id/tv_age"
        android:textColor="#440C0101"
        android:textSize="20sp"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/tv_sex"
        android:layout_marginTop="10dp"
        android:layout_marginStart="10dp"
        android:text="@string/tv_age"/>

    <EditText
        android:layout_width="240dp"
        android:layout_height="40dp"
        android:id="@+id/ev_age"
        android:textSize="20sp"
        android:textColor="#0A0101"
        android:layout_marginTop="10dp"
        android:layout_marginStart="20dp"
        android:layout_toEndOf="@+id/tv_age"
        android:layout_below="@+id/tv_sex"
        android:inputType="number"
        android:hint="@string/ev_age"
        android:imeOptions="actionDone"
        android:singleLine="true"/>

    <!--对于输入电话号码行-->
    <TextView
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:id="@+id/tv_tel"
        android:textColor="#440C0101"
        android:textSize="20sp"
        android:layout_alignParentStart="true"
        android:layout_marginTop="10dp"
        android:layout_marginStart="10dp"
        android:text="@string/tv_tel"
        android:layout_below="@+id/tv_age"/>

    <EditText
        android:layout_width="240dp"
        android:layout_height="40dp"
        android:id="@+id/ev_tel"
        android:textSize="20sp"
        android:textColor="#0A0101"
        android:layout_marginTop="10dp"
        android:layout_marginStart="20dp"
        android:layout_toEndOf="@+id/tv_age"
        android:layout_below="@+id/ev_age"
        android:inputType="phone"
        android:hint="@string/ev_tel"
        android:imeOptions="actionDone"
        android:singleLine="true"/>

    <!--对于班级输入行-->
    <TextView
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:id="@+id/tv_class"
        android:textColor="#440C0101"
        android:textSize="20sp"
        android:layout_alignParentStart="true"
        android:layout_marginStart="10dp"
        android:layout_below="@+id/tv_tel"
        android:layout_marginTop="10dp"
        android:text="@string/tv_class"/>

    <EditText
        android:layout_width="240dp"
        android:layout_height="40dp"
        android:id="@+id/ev_class"
        android:textSize="20sp"
        android:textColor="#0A0101"
        android:layout_marginTop="10dp"
        android:layout_marginStart="20dp"
        android:layout_below="@+id/ev_tel"
        android:layout_toEndOf="@+id/tv_class"
        android:hint="@string/ev_class"
        android:imeOptions="actionDone"
        android:singleLine="true"/>

    <!--对于女朋友姓名输入行-->
    <TextView
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:id="@+id/tv_girlfriend_name"
        android:textColor="#440C0101"
        android:textSize="20sp"
        android:layout_alignParentStart="true"
        android:layout_marginTop="10dp"
        android:layout_marginStart="10dp"
        android:layout_below="@+id/tv_class"
        android:text="@string/tv_girl_friend_name"/>

    <EditText
        android:layout_width="240dp"
        android:layout_height="40dp"
        android:id="@+id/ev_girlfriend_name"
        android:textSize="20sp"
        android:textColor="#0A0101"
        android:layout_marginTop="10dp"
        android:layout_marginStart="20dp"
        android:layout_toEndOf="@+id/tv_class"
        android:hint="@string/ev_girl_friend_name"
        android:layout_below="@+id/ev_class"
        android:imeOptions="actionDone"
        android:singleLine="true"/>

    <!--输入女朋友电话一行-->
    <TextView
        android:id="@+id/tv_girlfriend_tel"
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:layout_alignParentStart="true"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:textColor="#440C0101"
        android:textSize="20sp"
        android:layout_below="@+id/tv_girlfriend_name"
        android:text="@string/tv_girl_friend_tel"/>

    <EditText
        android:layout_width="240dp"
        android:layout_height="40dp"
        android:id="@+id/ev_girlfriend_tel"
        android:textSize="20sp"
        android:textColor="#0A0101"
        android:layout_marginTop="10dp"
        android:layout_marginStart="20dp"
        android:inputType="phone"
        android:layout_toEndOf="@+id/tv_girlfriend_name"
        android:layout_below="@+id/ev_girlfriend_name"
        android:hint="@string/ev_girl_friend_tel"
        android:imeOptions="actionDone"
        android:singleLine="true"/>

    <!--输入女朋友年龄一行-->
    <TextView
        android:id="@+id/tv_girlfriend_age"
        android:layout_width="120dp"
        android:layout_height="40dp"
        android:layout_alignParentStart="true"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:textColor="#440C0101"
        android:textSize="20sp"
        android:text="@string/tv_girl_friend_age"
        android:layout_below="@+id/tv_girlfriend_tel"/>

    <EditText
        android:layout_width="240dp"
        android:layout_height="40dp"
        android:id="@+id/ev_girlfriend_age"
        android:textSize="20sp"
        android:textColor="#0A0101"
        android:layout_marginTop="10dp"
        android:layout_marginStart="20dp"
        android:inputType="number"
        android:layout_toEndOf="@+id/tv_girlfriend_tel"
        android:layout_below="@+id/ev_girlfriend_tel"
        android:hint="@string/ev_girl_friend_age"
        android:imeOptions="actionDone"
        android:singleLine="true"/>

    <Button
        android:layout_width="80dp"
        android:layout_height="40dp"
        android:id="@+id/bt_save"
        android:layout_below="@+id/tv_girlfriend_age"
        android:layout_marginStart="40dp"
        android:layout_marginTop="20dp"
        android:textColor="#0A0101"
        android:text="@string/bt_save"/>

    <Button
        android:layout_width="80dp"
        android:layout_height="40dp"
        android:id="@+id/bt_update"
        android:layout_alignParentEnd="true"
        android:layout_marginEnd="40dp"
        android:layout_marginTop="20dp"
        android:textColor="#0A0101"
        android:layout_below="@+id/ev_girlfriend_age"
        android:text="@string/bt_update"/>

    <Button
        android:layout_width="80dp"
        android:layout_height="40dp"
        android:id="@+id/bt_create"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:textColor="#0A0101"
        android:layout_below="@+id/ev_girlfriend_age"
        android:text="@string/bt_create"/>


    <Button
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/bt_show"
        android:text="@string/bt_show"
        android:textColor="#0A0101"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/bt_update"
        />


</RelativeLayout>

第二步:添加必要的事件进行初始化,以及增加数据库保存等

public class MainActivity extends AppCompatActivity {

    TextView tv_name;
    TextView tv_sex;
    TextView tv_age;
    TextView tv_tel;
    TextView tv_class;
    TextView tv_girlfriend_name;
    TextView tv_girlfriend_tel;
    TextView tv_girlfriens_age;

    EditText et_name;
    Spinner sn_sex;
    EditText et_age;
    EditText et_tel;
    EditText et_class;
    EditText et_girlfriend_name;
    EditText et_girlfriend_tel;
    EditText et_girlfriend_age;

    //Button
    Button bt_save;
    Button bt_update;
    Button bt_create;
    Button bt_show;

    public DBHelperSub dbHelperSub;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initial();



    }


    //初始化函数
    public void initial()
    {

        dbHelperSub = new DBHelperSub(getApplicationContext(), "record.db", "personinfo_record", null, 2);

        tv_name = (TextView)findViewById(R.id.tv_name);
        tv_sex = (TextView)findViewById(R.id.tv_sex);
        tv_age = (TextView)findViewById(R.id.tv_age);
        tv_tel = (TextView)findViewById(R.id.tv_tel);
        tv_class = (TextView)findViewById(R.id.tv_class);
        tv_girlfriend_name = (TextView)findViewById(R.id.tv_girlfriend_name);
        tv_girlfriend_tel = (TextView)findViewById(R.id.tv_girlfriend_tel);
        tv_girlfriens_age = (TextView)findViewById(R.id.tv_girlfriend_age);

        et_name = (EditText)findViewById(R.id.ev_name);
        sn_sex = (Spinner)findViewById(R.id.sn_sex);
        et_age= (EditText)findViewById(R.id.ev_age);
        et_tel= (EditText)findViewById(R.id.ev_tel);
        et_class= (EditText)findViewById(R.id.ev_class);
        et_girlfriend_name= (EditText)findViewById(R.id.ev_girlfriend_name);
        et_girlfriend_tel= (EditText)findViewById(R.id.ev_girlfriend_tel);
        et_girlfriend_age= (EditText)findViewById(R.id.ev_girlfriend_age);

        bt_save = (Button)findViewById(R.id.bt_save);
        bt_update = (Button)findViewById(R.id.bt_update);
        bt_create = (Button)findViewById(R.id.bt_create);
        bt_show = (Button)findViewById(R.id.bt_show);

        bt_save.setClickable(false);
        bt_show.setClickable(false);
        //必要事件初始化——当失去焦点后,消除软键盘
        hideSoftInput();
        //必要事件初始化——对于按钮控件。
        btEvent_Initial();



    }

    //事件初始化
    public void btEvent_Initial()
    {
        bt_create.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(),"bt_create被点击",Toast.LENGTH_SHORT).show();


            }
        });

        bt_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Toast.makeText(getApplicationContext(),"bt_save被点击",Toast.LENGTH_SHORT).show();
                try {
                    DataBean dataBean = null;
                    dataBean = getContentList();
                    if (dataBean == null) {
                        return;
                    }


                    ContentValues values = new ContentValues();
                    values.put("name", dataBean.getName());
                    values.put("sex", dataBean.getSex());
                    values.put("age", dataBean.getAge());
                    values.put("phone", dataBean.getPhoneNumber());
                    values.put("girlfriend_name", dataBean.getGirlfriendName());
                    values.put("girlfriend_phone", dataBean.getGirlFriendTel());
                    values.put("girlfriend_age", dataBean.getGirlFriendAge());



                    SQLiteDatabase sqLiteDatabase = dbHelperSub.getWritableDatabase();

                    sqLiteDatabase.insert("personinfo_record", null, values);

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),"保存点击出错",Toast.LENGTH_SHORT).show();
                }
            }
        });

        bt_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Toast.makeText(getApplicationContext(),"bt_update被点击",Toast.LENGTH_SHORT).show();
                et_name.setText("");
                et_tel.setText("");
                et_age.setText("");
                et_girlfriend_name.setText("");
                et_girlfriend_age.setText("");
                et_girlfriend_tel.setText("");
            }
        });

        bt_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,ShowActivity.class);
                startActivity(intent);

            }
        });
    }

    //内容获取
    public DataBean getContentList()
    {
        DataBean dataBean = new DataBean();
        String str_name ;
        if (et_name.getText().toString().isEmpty())
        {
            Toast.makeText(getApplicationContext(),"存在未填完的项目,请填写完整!!!", Toast.LENGTH_SHORT).show();
            return null;
        }
        else
        {
            str_name = et_name.getText().toString();
        }

        String str_sex;
        if(sn_sex.getSelectedItemId()==0) {
            str_sex = "男";
        }
        else
        {
            str_sex = "女";
        }

        String str_tel;
        if(et_tel.getText().toString().isEmpty())
        {
            Toast.makeText(getApplicationContext(),"存在未填完的项目,请填写完整!!!", Toast.LENGTH_SHORT).show();
            return null;
        }
        else
        {
            str_tel = et_tel.getText().toString();
        }

        int int_age;
        if(et_age.getText().toString().isEmpty())
        {
            Toast.makeText(getApplicationContext(),"存在未填完的项目,请填写完整!!!", Toast.LENGTH_SHORT).show();
            return null;
        }
        else
        {
            int_age = Integer.valueOf(et_age.getText().toString()).intValue();
        }

        String str_class;
        if (et_class.getText().toString().isEmpty())
        {
            Toast.makeText(getApplicationContext(),"存在未填完的项目,请填写完整!!!", Toast.LENGTH_SHORT).show();
            return null;
        }
        else
        {
            str_class = et_class.getText().toString();
        }

        String str_girlfriend_name;
        if (et_girlfriend_name.getText().toString().isEmpty())
        {
            Toast.makeText(getApplicationContext(),"存在未填完的项目,请填写完整!!!", Toast.LENGTH_SHORT).show();
            return null;
        }
        else
        {
            str_girlfriend_name = et_girlfriend_name.getText().toString();
        }

        String str_girlfriend_tel;
        if (et_girlfriend_tel.getText().toString().isEmpty())
        {
            Toast.makeText(getApplicationContext(),"存在未填完的项目,请填写完整!!!", Toast.LENGTH_SHORT).show();
            return null;
        }
        else
        {
            str_girlfriend_tel = et_girlfriend_tel.getText().toString();
        }

        int int_girlfriend_age;
        if (et_girlfriend_age.getText().toString().isEmpty())
        {
            Toast.makeText(getApplicationContext(),"存在未填完的项目,请填写完整!!!", Toast.LENGTH_SHORT).show();
            return null;
        }
        else
        {
            int_girlfriend_age = Integer.valueOf(et_girlfriend_age.getText().toString()).intValue();
        }

        dataBean.setName(str_name);
        dataBean.setAge(int_age);
        dataBean.setSex(str_sex);
        dataBean.setPhoneNumber(str_tel);
        dataBean.setmClass(str_class);
        dataBean.setGirlfriendName(str_girlfriend_name);
        dataBean.setGirlFriendTel(str_girlfriend_tel);
        dataBean.setGirlFriendAge(int_girlfriend_age);

        return dataBean;
    }

    //必要事件初始化——当失去焦点后,消除软键盘
    public void hideSoftInput()
    {
        et_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {

                if(!b)
                {
                    InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
                }
            }
        });

        et_age.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {

                if(!b)
                {
                    InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
                }
            }
        });

        et_tel.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {

                if(!b)
                {
                    InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
                }
            }
        });

        et_class.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {

                if(!b)
                {
                    InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
                }
            }
        });

        et_girlfriend_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(!b)
                {
                    InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
                }
            }
        });

        et_girlfriend_age.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(!b)
                {
                    InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
                }
            }
        });

        et_girlfriend_tel.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if(!b)
                {
                    InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
                }
            }
        });

    }


}

第三步:新建一个与数据库有关的类,继承自SQLIteOpenHelper:

package com.example.sqlitepractice;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;

import java.io.Serializable;
import java.security.PublicKey;

public class DBHelperSub extends SQLiteOpenHelper implements Serializable {

    private String dbName;
    private Context context;
    private SQLiteDatabase.CursorFactory cursorFactory;
    private int version;
    private String tableName;

    private String CREATE_TABLE;

    public DBHelperSub(Context context, String dbName,String tableName,SQLiteDatabase.CursorFactory cursorFactory,int version)
    {
        super(context,dbName,cursorFactory,version);
        this.dbName = dbName;
        this.context = context;
        this.cursorFactory = cursorFactory;
        this.version = version;
        this.tableName = tableName;

        this.CREATE_TABLE ="create table if not exists personinfo_record (id integer primary key autoincrement not null,"
                +"name text not null,"
                +"sex text not null,"
                +"age integer not null,"
                +"phone text not null,"
                +"girlfriend_name text,"
                +"girlfriend_phone text,"
                +"girlfriend_age integer"
                +")";;

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        try {
            sqLiteDatabase.execSQL(CREATE_TABLE);
            Toast.makeText(context, "创建成功", Toast.LENGTH_SHORT).show();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            Toast.makeText(context, "创建失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

第四步:新建一个类,用于信息的保存与提取,相当于结构体的作用。

package com.example.sqlitepractice;

import android.widget.Spinner;

public class DataBean {

    private String name;
    private String sex;
    private String phoneNumber;
    private int age;
    private String mClass;
    private String girlfriendName;
    private String girlFriendTel;
    private int girlFriendAge;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public void setmClass(String mClass) {
        this.mClass = mClass;
    }

    public void setGirlfriendName(String girlfriendName) {
        this.girlfriendName = girlfriendName;
    }

    public void setGirlFriendTel(String girlFriendTel) {
        this.girlFriendTel = girlFriendTel;
    }

    public void setGirlFriendAge(int girlFriendAge) {
        this.girlFriendAge = girlFriendAge;
    }

    public String getName() {
        return name;
    }

    public String getSex() {
        return sex;
    }

    public int getAge() {
        return age;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public String getGirlfriendName() {
        return girlfriendName;
    }

    public String getGirlFriendTel() {
        return girlFriendTel;
    }

    public int getGirlFriendAge() {
        return girlFriendAge;
    }

}

第四步:新建一个页面Activity显示数据库中保存的信息

package com.example.sqlitepractice;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.CharArrayBuffer;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.io.Serializable;

public class ShowActivity extends AppCompatActivity {

    DBHelperSub dbHelperSub;
    TextView textView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);

        textView = (TextView)findViewById(R.id.tv_show);


        SQLiteDatabase database = getApplication().openOrCreateDatabase("record.db", 0, null);
        if(database.isOpen())
        {

            String sql = "select * from personinfo_record";
            Cursor cursor = database.rawQuery(sql.toString(), null);

            if(cursor !=null)
            {
                cursor.moveToFirst();
                //Toast.makeText(getApplicationContext(),String.valueOf(cursor.getString(cursor.getColumnIndex("name"))), Toast.LENGTH_SHORT).show();
                while (cursor.moveToNext())
                {
                    textView.append(cursor.getString(cursor.getColumnIndex("name")));
                }
                //Toast.makeText(getApplicationContext(), cursor.getString(cursor.getColumnIndex("name")), Toast.LENGTH_SHORT).show();
            }

        }


    }
}

以上就是全部的内容。如果有问题可以询问:

QQ:476596998

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!