Android存储数据的三种方式

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/ZackSock/article/details/100943825

今天来给大家讲一下Android中如何存储数据。我编写Android使用的是Java语言,所以今天讲的也是Java版的数据存储。在Android中,数据存储主要有三种,文件存储、Sp、SQLite。文件存储就是我们平时的IO流,是非常传统的一种方式。而Sp是Android中的,利用XML文件存储数据的一种方式,要比文件存储简单。SQLite就是一个数据库了,基本操作和数据库大致一样。

1、文件存储

先写一个简洁的登陆界面:

布局文件activity_main.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="用户名"/>

    <EditText
        android:id="@+id/et_pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:hint="密码"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="save"
        android:text="登录"/>

</LinearLayout>

MainActivity中基本代码如下,就是简单的声明控件和关联控件:

public class MainActivity extends AppCompatActivity {
    //声明控件
    private EditText etName;
    private EditText etPwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }
    private void initView() {
        //关联控件
        etName = findViewById(R.id.et_name);
        etPwd = findViewById(R.id.et_pwd);
    }
}

1.1、保存文件

接下来实现一下点击事件save():

public void save(View view) {
    //当用户名密码不为空时
    if(!TextUtils.isEmpty(etName.getText()) && !TextUtils.isEmpty(etPwd.getText())){
        FileOutputStream fos = null;
        try {


            //Context中的方法openFileOutput(),获取一个FileOutputStream对象
            fos = openFileOutput("data", Context.MODE_PRIVATE);
            String str = etName.getText().toString().trim() + "#" + etPwd.getText().toString().trim();
            fos.write(str.getBytes());
            Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();



        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }else{
        Toast.makeText(getApplicationContext(), "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
    }
}

代码看起来有点乱,我在中间空了许多,主要代码就那些。利用Context中的openFileOutput(String name, int mode)方法,传入文件名和操作模式。获取一个FileOutputStream对象,然后在存储文件。我这里直接用#来拼接,这样是有问题的。这里只是为了方便。

1.2、读取文件

我们写一个方法load,用来读取文件:

private void load() {
    try{
        //利用Context中的openFileInput()方法获取输入流
        FileInputStream data = openFileInput("data");
        BufferedReader reader = new BufferedReader(new InputStreamReader(data));
        String line = reader.readLine();
        String[] split = line.split("#");
        etName.setText(split[0]);
        etPwd.setText(split[1]);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这里使用了Context中的openFileInput()方法,获取流,然后读取文件。因为文件流比较少用,我就讲到这里。

2、SharedPreferences简称Sp

Sp是一种用xml文件存储数据的方式,下面我具体讲一下。

2.1、Sp的创建

sp的创建方式有三种,第一种,之直接使用Context中的getSharedPreferences()方法,传入文件名和操作模式:

private void initView(){
    //使用Context中的getSharedPreferences方法获取Sp对象
    SharedPreferences sp = getSharedPreferences("data", Context.MODE_PRIVATE);
}

第二种,使用Activity中的getPreferences()方法,传入一个操作模式,文件名自动以类名命名:

SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);

第三种,使用PreferenceManager中的getDefaultPreferences()方法,传入一个Context参数:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

2.2、用Sp保存数据

使用Editor对象存储,Editor中对应的数据类型有对应的方法。putString、putInt...

private void initData(){
    //获取sp对象
    SharedPreferences sp = getSharedPreferences("data", Context.MODE_PRIVATE);

    //获取Editor对象
    SharedPreferences.Editor editor = sp.edit();

    //用Editor对象储存数据,传入键和值
    editor.putString("name", "zack");

    //最后调用apply()方法
    editor.apply();
    
}

2.3、获取Sp中的文件

获取的时候直接用存储时的文件名创建一个Sp对象,就可以读取数据:

private void initData(){
    //创建一个文件名为data的sp对象
    SharedPreferences sp = getSharedPreferences("data", Context.MODE_PRIVATE);
    
    //直接通过键获取数据,如果通过这个键找不到,就返回第二个参数中的值
    sp.getString("name", null);
    
}

3、SQLite数据库

3.1、SQLite数据库的创建

SQLite数据库的创建需要实现抽象类SQLiteOpenHelper,具体先定义一个类MySQLiteOpenHelper继承SQLiteOpenHelper:

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

    /**
     * @param context 上下文
     * @param name    数据库名称
     * @param factory   游标工场
     * @param version   版本
     */
    public MySQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    /**
     *  数据库创建时调用这个方法
     * @param db    数据库对象
     */
    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    /**
     *  数据库升级的时候自动调用
     * @param db    数据库对象
     * @param oldVersion    老版本
     * @param newVersion    新版本
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

这里写了三个方法,其中onCreate()和onUpgrade()方法为SQLiteOpenHelper中的抽象方法。onCreate()在数据库创建时调用,只。而onUpgrade()在数据库升级时调用()(Version改变时)。所以onCreate()用于初始化表结构、onUpgrade()用于更新表结构。调用db.execSQL()方法,传入一个SQL语句就好了。

3.2、获取数据库

在Activity中创建MySQLiteOpenHelper的实例,然后通过这个实例获取数据库:

private void initData(){
    //这里游标工场暂时用不到,设为null
    MySQLiteOpenHelper sqLiteOpenHelper = new MySQLiteOpenHelper(this, "db", null, 1);
    
    //通过MySQLiteOpenHelper对象获取数据。这两个方法暂时不区别
    //SQLiteDatabase db = sqLiteOpenHelper.getWritableDatabase();
    SQLiteDatabase db = sqLiteOpenHelper.getReadableDatabase();

}

3.3、数据库操作

因为篇幅的关系,这里先不讲这么多了。SQLite中可以调用DataBase对象的execSQL()方法,通过SQL语句完成大多数操作。具体Android中特有的操作后面我再讲。大家有兴趣的话可以去了解一下郭林大神的LitePal,用来操作SQLite数据库方便很多。

猜你喜欢

转载自blog.csdn.net/ZackSock/article/details/100943825
今日推荐