Android内部存储:SharedPreferences(存储xml文件)、File(存储INI文件)、OrmLite(数据库)

感觉我的笔记本最近卡的,随时得死机😑,还是把一些代码记录一下,毕竟现在想找去年的代码已经不知道哪去了🙃,而且找到了我也看不懂我写的啥

这篇记录一下Android的内部存储。简单总结一下(个人理解):

  • SharedPreferences方式用键值对存数据,目标文件是 .xml格式的,最后存的数据类似于(期末考试我就写错标签了💀):

<string name=“键”>值</string>

  • File方式能指定文件的名字与格式,例如配置信息文件常用格式 .ini,当然这个你可以随意指定,什么 .txt.c.h.py……都行,最后的目标文件就是 xxx.xx(例如 config.ini),都是你自己取的。
  • 数据库就是用按数据库的方式存值了,更加高级的方式,自然会更难一点。

废话不多说了,直接贴代码。

目录结构

如下图:

主页面

一共四种功能测试,分成四个activity,主界面弄成导航。

  • activity_main.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"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:padding="10dp">

    <Button
        android:id="@+id/SP"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="SharedPreferences存储数据"
        android:textSize="20sp"
        android:background="@drawable/bg_buttonchange"
        android:layout_gravity="center"/>

    <Button
        android:id="@+id/saveconf"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="SharedPreferences存储配置信息"
        android:textSize="20sp"
        android:background="@drawable/bg_buttonchange"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"/>

    <Button
        android:id="@+id/saveini"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="File存储INI配置信息"
        android:textColor="#000000"
        android:textSize="20sp"
        android:background="@drawable/bg_buttonchange"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"/>

    <Button
        android:id="@+id/ORM"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="OrmLite数据库"
        android:textSize="20sp"
        android:background="@drawable/bg_buttonchange"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"/>


</LinearLayout>
  • MainActivity.java
public class MainActivity extends AppCompatActivity {
    private Button savebutton, litebutton, saveconfbutton, saveini;

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

        savebutton = findViewById(R.id.SP);
        litebutton = findViewById(R.id.ORM);
        saveconfbutton = findViewById(R.id.saveconf);
        saveini = findViewById(R.id.saveini);

        savebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SharedPreferencesActivity.class);
                startActivity(intent);
            }
        });

        litebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,OrmLiteActivity.class);
                startActivity(intent);
            }
        });

        saveconfbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,SaveConfigActivity.class);
                startActivity(intent);
            }
        });

        saveini.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,SaveiniActivity.class);
                startActivity(intent);
            }
        });
    }
}
  • bg_buttonchange.xml(我给按钮都设了一样的样式:圆角、透明、按下变蓝色,放在drawable里就行。)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid
                android:color="#2BD5FF" />
            <corners
                android:radius="30dp" />
        </shape>
    </item>

    <item android:state_pressed="false">
        <shape>
            <stroke
                android:color="#807C7C"
                android:width="2dp"/>
            <corners
                android:radius="30dp"/>
        </shape>
    </item>
</selector>

  • 界面效果

SharedPreferences存储数据

  • activity_shared_preferences.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"
    tools:context=".SharedPreferencesActivity"
    android:orientation="vertical"
    android:padding="10dp">

    <EditText
        android:id="@+id/data"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/bg_circle"
        android:hint="点击输入想要储存的数据"
        android:paddingLeft="5dp"/>
    
    <Button
        android:id="@+id/save"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:background="@drawable/bg_buttonchange"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:text="储存数据"
        android:textSize="25sp"/>

    <Button
        android:id="@+id/read"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:background="@drawable/bg_buttonchange"
        android:layout_gravity="center"
        android:textSize="25sp"
        android:text="读取数据"
        android:layout_marginTop="20dp"/>

    <TextView
        android:id="@+id/show"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_marginTop="50dp"/>
    
</LinearLayout>
  • SharedPreferencesActivity.java
public class SharedPreferencesActivity extends AppCompatActivity {

    private EditText data;
    private Button save,read;
    private TextView show;
    private SharedPreferences msharedPreferences;       //定义一个SharedPreferences类,用于读数据
    private SharedPreferences.Editor meditor;       //定义一个SharedPreferences.Editor类,用于写数据

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

        data = findViewById(R.id.data);
        save = findViewById(R.id.save);
        read = findViewById(R.id.read);
        show = findViewById(R.id.show);

        msharedPreferences = getSharedPreferences("mydata",MODE_PRIVATE);       //获取实例化对象,该文件的名字是“mydata”,私有模式,只能由调用的应用程序访问
        meditor = msharedPreferences.edit();        //同上,获取一个能执行写操作的对象

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = data.getText().toString();
                meditor.putString("mydata",str);        //以键值对的方式写入“mydata.xml”文件中,此时并没有提交到内存
                meditor.apply();        //meditor.commit();也行,一个是同步一个是异步,必须要这一步!只写上一句没用
                Toast.makeText(getApplicationContext(),"写入成功!",Toast.LENGTH_SHORT).show();
            }
        });

        read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = msharedPreferences.getString("mydata","ERROR");        //以键值对的形式读数据,键就是上面存的时候的键,第二个参数是如果没读到返回的默认值
                Toast.makeText(getApplicationContext(),str,Toast.LENGTH_SHORT).show();
                show.setText(str);
            }
        });
    }
}
  • 现象展示

SharedPreferences储存配置信息(很傻的办法)

  • activity_save_config.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"
    tools:context=".SaveConfigActivity"
    android:orientation="vertical"
    android:padding="10dp"
    android:id="@+id/bgcolor">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="设置背景颜色"
        android:textSize="25sp"
        android:textColor="#000000"/>

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/blue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="蓝色"
            android:textSize="20sp"
            android:textColor="#000000"
            android:onClick="myColorClick"/>

        <RadioButton
            android:id="@+id/red"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="红色"
            android:textColor="#000000"
            android:textSize="20sp"
            android:layout_marginTop="10dp"
            android:onClick="myColorClick"/>

        <RadioButton
            android:id="@+id/green"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="绿色"
            android:textSize="20sp"
            android:textColor="#000000"
            android:layout_marginTop="10dp"
            android:onClick="myColorClick"/>

    </RadioGroup>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="设置字体大小"
        android:textSize="25sp"
        android:textColor="#000000"
        android:layout_marginTop="20dp"/>

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/small"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="小号"
            android:textSize="20sp"
            android:textColor="#000000"
            android:onClick="mySizeClick"/>

        <RadioButton
            android:id="@+id/middle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="中号"
            android:textColor="#000000"
            android:textSize="20sp"
            android:layout_marginLeft="10dp"
            android:onClick="mySizeClick"/>

        <RadioButton
            android:id="@+id/big"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="大号"
            android:textSize="20sp"
            android:textColor="#000000"
            android:layout_marginLeft="10dp"
            android:onClick="mySizeClick"/>

    </RadioGroup>

</LinearLayout>
  • SaveConfigActivity.java
public class SaveConfigActivity extends AppCompatActivity {
    private LinearLayout linearLayout;
    private RadioButton small,middle,big;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    String backgrondcolor = "",textsize = "";

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

        linearLayout = findViewById(R.id.bgcolor);
        small = findViewById(R.id.small);
        middle = findViewById(R.id.middle);
        big = findViewById(R.id.big);

        sharedPreferences = getSharedPreferences("config",MODE_PRIVATE);
        editor = sharedPreferences.edit();

        checkconfig();

        Toast.makeText(getApplicationContext(),"页面启动!",Toast.LENGTH_SHORT).show();
    }

    public void myColorClick(View v){
        switch (v.getId()){
            case R.id.blue:
                linearLayout.setBackgroundColor(Color.BLUE);
                backgrondcolor = "blue";
                Toast.makeText(getApplicationContext(),"蓝色",Toast.LENGTH_SHORT).show();
                break;
            case R.id.red:
                linearLayout.setBackgroundColor(Color.RED);
                backgrondcolor = "red";
                Toast.makeText(getApplicationContext(),"红色",Toast.LENGTH_SHORT).show();
                break;
            case R.id.green:
                linearLayout.setBackgroundColor(Color.GREEN);
                backgrondcolor = "green";
                Toast.makeText(getApplicationContext(),"绿色",Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        editor.putString("backgrondcolor",backgrondcolor);
        editor.apply();
    }

    public void mySizeClick(View v){
        switch (v.getId()){
            case R.id.small:
                small.setTextSize(10);
                middle.setTextSize(10);
                big.setTextSize(10);
                textsize = "small";
                Toast.makeText(getApplicationContext(),"小号",Toast.LENGTH_SHORT).show();
                break;
            case R.id.middle:
                small.setTextSize(20);
                middle.setTextSize(20);
                big.setTextSize(20);
                textsize = "middle";
                Toast.makeText(getApplicationContext(),"中号",Toast.LENGTH_SHORT).show();
                break;
            case R.id.big:
                small.setTextSize(30);
                middle.setTextSize(30);
                big.setTextSize(30);
                textsize = "big";
                Toast.makeText(getApplicationContext(),"大号",Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        editor.putString("textsize",textsize);
        editor.apply();
    }

    public void checkconfig(){
        String bg = sharedPreferences.getString("backgrondcolor","");
        String ts = sharedPreferences.getString("textsize","");

//        Toast.makeText(getApplicationContext(),bg+" "+ts,Toast.LENGTH_SHORT).show();

        if (bg.equals("blue")){
            linearLayout.setBackgroundColor(Color.BLUE);
        }
        else if (bg.equals("red")){
            linearLayout.setBackgroundColor(Color.RED);
        }
        else if (bg.equals("green")){
            linearLayout.setBackgroundColor(Color.GREEN);
        }
        else {

        }

        if (ts.equals("small")){
            small.setTextSize(10);
            middle.setTextSize(10);
            big.setTextSize(10);
        }
        else if (ts.equals("middle")){
            small.setTextSize(20);
            middle.setTextSize(20);
            big.setTextSize(20);
        }
        else if (ts.equals("big")){
            small.setTextSize(30);
            middle.setTextSize(30);
            big.setTextSize(30);
        }
        else {

        }
    }
}
  • 效果展示

File存储.ini文件

其实效果跟上一个一样,只是使用File方式存了个 .ini后缀的文件(依然很蠢的办法 )。

  • activity_saveini.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"
    tools:context=".SaveiniActivity"
    android:orientation="vertical"
    android:padding="10dp"
    android:id="@+id/bgcolor">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="设置背景颜色"
        android:textSize="25sp"
        android:textColor="#000000"/>

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RadioButton
            android:id="@+id/blue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="蓝色"
            android:textSize="20sp"
            android:textColor="#000000"
            android:onClick="myColorClick"/>

        <RadioButton
            android:id="@+id/red"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="红色"
            android:textColor="#000000"
            android:textSize="20sp"
            android:layout_marginTop="10dp"
            android:onClick="myColorClick"/>

        <RadioButton
            android:id="@+id/green"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="绿色"
            android:textSize="20sp"
            android:textColor="#000000"
            android:layout_marginTop="10dp"
            android:onClick="myColorClick"/>

    </RadioGroup>

</LinearLayout>
  • SaveiniActivity.java
public class SaveiniActivity extends AppCompatActivity {
    private LinearLayout linearLayout;
    String backgrondcolor = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_saveini);

        linearLayout = findViewById(R.id.bgcolor);

        try {
            checkconfig();

        } catch (IOException e) {
            e.printStackTrace();
        }

        Toast.makeText(getApplicationContext(),"页面启动!",Toast.LENGTH_SHORT).show();
    }

    public void myColorClick(View v) throws IOException {
        switch (v.getId()){
            case R.id.blue:
                linearLayout.setBackgroundColor(Color.BLUE);
                backgrondcolor = "blue";
                Toast.makeText(getApplicationContext(),"蓝色",Toast.LENGTH_SHORT).show();
                break;
            case R.id.red:
                linearLayout.setBackgroundColor(Color.RED);
                backgrondcolor = "red";
                Toast.makeText(getApplicationContext(),"红色",Toast.LENGTH_SHORT).show();
                break;
            case R.id.green:
                linearLayout.setBackgroundColor(Color.GREEN);
                backgrondcolor = "green";
                Toast.makeText(getApplicationContext(),"绿色",Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        savefile();
    }

    private void savefile() throws IOException {
        FileOutputStream out = this.openFileOutput("config.ini", Context.MODE_PRIVATE);     //获取一个文件输出流实例对象,名字自己取,后缀也可以自己取,模式和sharedPreferences的一样
        out.write(backgrondcolor.getBytes());       //把背景颜色字符串转换成比特流写进“config.ini”文件里
        out.close();        //关闭连接
        Toast.makeText(getApplicationContext(),"文件储存成功!",Toast.LENGTH_SHORT).show();
    }

    public void checkconfig() throws IOException {
        FileInputStream in = this.openFileInput("config.ini");      //获取输入流对象
        ByteArrayOutputStream stream = new ByteArrayOutputStream();     //对比特流数据写入就要用这个类,作为一个中间商,转换用
        byte[] bytes = new byte[1024];
        int length = -1;
        if((length = in.read(bytes)) != -1){        //读输入流到比特数组中,读出来的数据长度如果不为-1,即无数据,
            stream.write(bytes,0,length);       //就把这些数据从比特数组中转换进上面的中间商里,也就是这个byte数组的输出流
        }
        stream.close();
        in.close();
        String bg = stream.toString();      //这个byte数组的输出流就能直接用toString()来转换

//        Toast.makeText(getApplicationContext(),bg+" "+ts,Toast.LENGTH_SHORT).show();

        if (bg.equals("blue")){
            linearLayout.setBackgroundColor(Color.BLUE);
        }
        else if (bg.equals("red")){
            linearLayout.setBackgroundColor(Color.RED);
        }
        else if (bg.equals("green")){
            linearLayout.setBackgroundColor(Color.GREEN);
        }
        else {

        }
    }

}
  • 效果跟上一个一样。

OrmLite存储员工信息

这是个第三方的数据库,需要引入依赖库才能用,方法网上很多。

  • Staff.java
@DatabaseTable(tableName = "staff")     //注释方式,使该类成为一个表,表名不指定默认为类名
public class Staff {
    @DatabaseField(generatedId = true)      //ID是否自动增加
    private int id;
    @DatabaseField      //属性
    private String name;
    @DatabaseField
    private String sex;
    @DatabaseField
    private String department;
    @DatabaseField
    private float salary;

    public Staff(){

    }

    public Staff(String name, String sex, String department, float salary){
        this.name = name;
        this.sex = sex;
        this.department = department;
        this.salary = salary;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getSex() {
        return sex;
    }

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

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public float getSalary() {
        return salary;
    }

    public void setSalary(float salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "staff{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", department='" + department + '\'' +
                ", salary=" + salary +
                '}';
    }
}
  • DatebaseHelper.java
public class DatebaseHelper extends OrmLiteSqliteOpenHelper {

    private DatebaseHelper(Context context) {
        super(context, "test.db", null, 1);     //上下文为调用方传入,一般是主UI,数据库名位test.db,游标为空,版本号为1
    }

    private static DatebaseHelper selfHelper = null;

    public static synchronized DatebaseHelper getInstance(Context context){
        if(selfHelper == null){
            selfHelper = new DatebaseHelper(context);       //创建数据库helper类实例对象
        }
        return selfHelper;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, Staff.class);      //建表
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        try {
            TableUtils.dropTable(connectionSource, Staff.class,true);
            onCreate(sqLiteDatabase,connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
  • StaffDao.java
public class StaffDao {

    Context context;
    String TAG = "StaffDao";

    public StaffDao(Context context){
        this.context = context;
    }

    public DatebaseHelper getMyHelper(){
        return DatebaseHelper.getInstance(context);     //返回一个helper的实例对象
    }

    public Dao<Staff,Integer> getStaffDao() throws SQLException {
        return getMyHelper().getDao(Staff.class);       //通过helper对象获取到Dao对象,然后就可以通过Dao对象对数据库进行增删查改等操作
    }

    public void testInsert(String name,String sex,String department,float salary) throws SQLException{
        Dao<Staff,Integer> staffDao = getStaffDao();
        Staff staff = new Staff(name,sex,department,salary);
        staffDao.create(staff);     //创建一条记录,即插入操作
    }

    public Staff testQuery(Integer id) throws SQLException{
        Dao<Staff,Integer> staffDao = getStaffDao();
//        List<Staff> staffs = staffDao.queryForAll();
//        for(Staff staff : staffs){
//            Log.e(TAG,"查询所有数据:\r\n"+staff.toString());
//        }
        Staff staff = staffDao.queryForId(id);      //通过ID查询一项纪录
        return staff;       //并返回这个记录的对象
    }

    public List<Staff> testQueryAll() throws SQLException{
        Dao<Staff,Integer> staffDao = getStaffDao();
        List<Staff> staffs = staffDao.queryForAll();        //查询该表中的所有记录,返回一个Staff泛型的list
        return staffs;
    }

    public void testUpdate(Integer id,String name,String sex,String department,float salary) throws SQLException{
        Dao<Staff,Integer> staffDao = getStaffDao();

        UpdateBuilder update = staffDao.updateBuilder();

        update.setWhere(update.where().eq("id",id));        //类似于SQL的where关键字,设定更新的条件

        update.updateColumnValue("name",name);      //通过列名更新具体的记录
        update.updateColumnValue("sex",sex);
        update.updateColumnValue("department",department);
        update.updateColumnValue("salary",salary);

        update.update();        //把这个更新记录提交Dao对象的更新“者”(builder)去更新
    }

    public void testDelete(Integer id) throws SQLException{
        Dao<Staff,Integer> staffDao = getStaffDao();
        staffDao.deleteById(id);        //通过ID删除
    }
}
  • activity_orm_lite.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"
    tools:context=".OrmLiteActivity"
    android:orientation="vertical"
    android:padding="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:text="姓名:"
            android:textSize="25sp"
            android:gravity="center"/>

        <EditText
            android:id="@+id/name"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="8"
            android:background="@drawable/bg_circle"
            android:hint="点击输入姓名"
            android:paddingLeft="5dp"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingTop="10dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:text="性别:"
            android:textSize="25sp"
            android:gravity="center"/>

        <EditText
            android:id="@+id/sex"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="8"
            android:background="@drawable/bg_circle"
            android:hint="点击输入性别"
            android:paddingLeft="5dp"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingTop="10dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:text="部门:"
            android:textSize="25sp"
            android:gravity="center"/>

        <EditText
            android:id="@+id/department"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="8"
            android:background="@drawable/bg_circle"
            android:hint="点击输入部门"
            android:paddingLeft="5dp"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingTop="10dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:text="工资:"
            android:textSize="25sp"
            android:gravity="center"/>

        <EditText
            android:id="@+id/salary"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="8"
            android:background="@drawable/bg_circle"
            android:hint="点击输入工资"
            android:paddingLeft="5dp"/>

    </LinearLayout>

    <Button
        android:id="@+id/create"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="插入数据"
        android:textSize="20sp"
        android:background="@drawable/bg_buttonchange"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingTop="10dp">

        <TextView
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:text="ID:"
            android:textSize="25sp"
            android:gravity="center"/>

        <EditText
            android:id="@+id/id"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="8"
            android:background="@drawable/bg_circle"
            android:hint="点击输入ID"
            android:paddingLeft="5dp"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="15dp">

        <Button
            android:id="@+id/query"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:text="ID查询"
            android:textSize="20sp"
            android:background="@drawable/bg_buttonchange"
            android:layout_gravity="center" />

        <Button
            android:id="@+id/update"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:text="ID更新"
            android:textSize="20sp"
            android:background="@drawable/bg_buttonchange"
            android:layout_gravity="center"
            android:layout_marginLeft="10dp"/>

        <Button
            android:id="@+id/delete"
            android:layout_width="0dp"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:text="ID删除"
            android:textSize="20sp"
            android:background="@drawable/bg_buttonchange"
            android:layout_gravity="center"
            android:layout_marginLeft="10dp"/>

    </LinearLayout>

    <Button
        android:id="@+id/queryall"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@drawable/bg_buttonchange"
        android:layout_marginTop="10dp"
        android:text="查询所有数据"
        android:textSize="20sp"/>

    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="10dp"
        android:layout_marginTop="10dp"/>

</LinearLayout>

页面长这样

  • OrmLiteActivity.java
public class OrmLiteActivity extends AppCompatActivity implements View.OnClickListener {
    private StaffDao staffDao;
    private Button create,query,update,delete,queryall;
    private EditText id,name,sex,department,salary;
    private Staff staff;
    private List<Staff> staffs;
    private TextView result;

    String TAG = "OrmLiteActivity";

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

        staffDao = new StaffDao(this);      //第一次把当前上下文传进去,就会创建一个数据库,得到的对象就可以直接调用公有方法来操作数据库了

        init();
    }

    private void init(){
        create = findViewById(R.id.create);
        query = findViewById(R.id.query);
        update = findViewById(R.id.update);
        delete = findViewById(R.id.delete);
        id = findViewById(R.id.id);
        name = findViewById(R.id.name);
        sex = findViewById(R.id.sex);
        department = findViewById(R.id.department);
        salary = findViewById(R.id.salary);
        result = findViewById(R.id.result);
        queryall = findViewById(R.id.queryall);

        create.setOnClickListener(this);
        query.setOnClickListener(this);
        update.setOnClickListener(this);
        delete.setOnClickListener(this);
        queryall.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String Name = name.getText().toString();
        String Sex = sex.getText().toString();
        String Department = department.getText().toString();
        String Salary = salary.getText().toString();
        String Id = id.getText().toString();

        switch (v.getId()){
            case R.id.create:
                try {
                    if (Name.equals("") || Sex.equals("") || Department.equals("") || Salary.equals("")){
                        Toast.makeText(getApplicationContext(),"输入不能为空!",Toast.LENGTH_SHORT).show();
                        break;
                    }
                    staffDao.testInsert(Name, Sex, Department,Integer.parseInt(Salary));
                    Toast.makeText(getApplicationContext(),"插入成功!",Toast.LENGTH_SHORT).show();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.query:
                try {
                    if (Id.equals("")){
                        Toast.makeText(getApplicationContext(),"请输入ID!",Toast.LENGTH_SHORT).show();
                        break;
                    }
                    staff = staffDao.testQuery(Integer.parseInt(Id));
                    Toast.makeText(getApplicationContext(),"查询成功!",Toast.LENGTH_SHORT).show();
                    Log.i(TAG,"\r\n"+staff.toString());
                    result.setText(staff.toString());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.queryall:
                try {
                    String str = "";
                    staffs = staffDao.testQueryAll();
                    Toast.makeText(getApplicationContext(),"查询成功!",Toast.LENGTH_SHORT).show();
                    for(Staff staff:staffs){
                        Log.i(TAG,"\r\n"+staff.toString());
                        str += staff.toString()+"\r\n\r\n";
                    }
                    result.setText(str);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.update:
                try {
                    if (Id.equals("")){
                        Toast.makeText(getApplicationContext(),"请输入ID!",Toast.LENGTH_SHORT).show();
                        break;
                    }
                    staffDao.testUpdate(Integer.parseInt(Id),
                            Name, Sex,Department,Integer.parseInt(Salary));
                    Toast.makeText(getApplicationContext(),"修改成功!",Toast.LENGTH_SHORT).show();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.delete:
                try {
                    if (Id.equals("")){
                        Toast.makeText(getApplicationContext(),"请输入ID!",Toast.LENGTH_SHORT).show();
                        break;
                    }
                    staffDao.testDelete(Integer.parseInt(Id));
                    Toast.makeText(getApplicationContext(),"删除成功!",Toast.LENGTH_SHORT).show();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
}
  • 效果展示


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值