This is the 9th day of my participation in the Novembermore Challenge.The final text challenge in 2021

Today I’m going to tell you how to store data in Android. I wrote Android in The Java language, so this is the Java version of the data store. In Android, there are three main types of data storage: file storage, Sp and SQLite. File storage is our usual IO stream, is a very traditional way. Sp is an Android way of storing data using XML files, which is much simpler than file storage. SQLite is a database, and the basic operations are much the same as a database.

1. File storage

Write a simple login interface:

The layout file activity_main.xml looks like this:

<? The 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=" username "/> <EditText Android :id="@+id/et_pwd" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" <Button android:layout_width="match_parent" Android :layout_height="wrap_content" Android :onClick="save" Android :text=" login "/> </LinearLayout>Copy the code

The basic code for MainActivity is as follows: simple declarative controls and associated controls:

Public class MainActivity extends AppActivity {private EditText etName; private EditText etPwd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() {// Associate control etName = findViewById(r.id.ett_name); etPwd = findViewById(R.id.et_pwd); }}Copy the code

1.1. Save the file

Next, click the event Save () :

Public void save(View View) {// If (! TextUtils.isEmpty(etName.getText()) && ! TextUtils.isEmpty(etPwd.getText())){ FileOutputStream fos = null; Fos = openFileOutput("data", context.mode_private); String str = etName.getText().toString().trim() + "#" + etPwd.getText().toString().trim(); fos.write(str.getBytes()); Toast.maketext (getApplicationContext(), "save successful ", toast.length_short).show(); } catch (Exception e) { e.printStackTrace(); } finally { try { fos.close(); } catch (IOException e) { e.printStackTrace(); }}else{toast.makeText (getApplicationContext(), "user name or password cannot be empty ", toast.length_short).show(); }}Copy the code

The code looks a little messy, and I left a lot of space in the middle, but that’s the main code. Using the openFileOutput(String Name, int Mode) method in Context, pass in the file name and operation mode. Get a FileOutputStream object and store the file. I’m just going to use # here, which is a problem. This is just for convenience.

1.2. Read files

We’ll write a load method to load the file:

FileInputStream data = openFileInput("data"); private void load() {try{// Use Context openFileInput() to get input streams. 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(); }}Copy the code

Here we use the openFileInput() method in the Context, get the stream, and then read the file. I’m going to stop there because file streams are used less often.

2. SharedPreferences

Sp is a way to store data in XML files, which I’ll talk about in detail.

2.1 Creation of Sp

First, use the getSharedPreferences() method in the Context, passing in the file name and the preferences mode:

Private void initView(){getSharedPreferences Sp = getSharedPreferences("data", Context.MODE_PRIVATE); }Copy the code

Second, use the getPreferences() method in the Activity to pass in an action mode with the file name automatically named after the class name:

SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
Copy the code

Third, using the getDefaultPreferences() method in the PreferenceManager, passing in a Context parameter:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Copy the code

2.2. Use Sp to save data

The Editor object is used for storage, and the corresponding data type in the Editor has corresponding methods. PutString and putInt…

SharedPreferences sp = getSharedPreferences("data", context.mode_private); SharedPreferences.Editor Editor = sp.edit(); Editor.putstring ("name", "zack"); // Finally call the apply() method editor.apply(); }Copy the code

2.3. Obtain files in Sp

Create a Sp object with the name of the file stored at the time;

Private void initData(){SharedPreferences sp = getSharedPreferences("data", context.mode_private); Sp.getstring ("name", null); sp.getString("name", null); }Copy the code

3. SQLite database

3.1. Creation of SQLite database

SQLiteOpenHelper (MySQLiteOpenHelper); SQLiteOpenHelper (MySQLiteOpenHelper); SQLiteOpenHelper (MySQLiteOpenHelper);

Public class MySQLiteOpenHelper extends SQLiteOpenHelper {/** * @param Context context * @param name Database name * @param Factory Public MySQLiteOpenHelper(Context Context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @override public void onCreate(SQLiteDatabase db) {} /** * Automatically called when the database is upgraded @param db database object * @param oldVersion oldVersion * @param newVersion newVersion */ @override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }Copy the code

Three methods are written here, of which the onCreate() and onUpgrade() methods are abstract methods in SQLiteOpenHelper. OnCreate () is called when the database is created, only. OnUpgrade (), on the other hand, calls () when the database is upgraded (when Version changes). So onCreate() is used to initialize the table structure and onUpgrade() is used to update it. Call the db.execSQL() method and pass in an SQL statement.

3.2. Get the database

Create an instance of MySQLiteOpenHelper in your Activity and get the database from that instance:

Private void initData(){// Set MySQLiteOpenHelper to null sqLiteOpenHelper = new MySQLiteOpenHelper(this, "db", null, 1); // Get data from MySQLiteOpenHelper. These two methods temporarily no difference / / SQLiteDatabase db = sqLiteOpenHelper getWritableDatabase (); SQLiteDatabase db = sqLiteOpenHelper.getReadableDatabase(); }Copy the code

3.3. Database operation

For the sake of space, I won’t talk about that much here. In SQLite, you can call the execSQL() method of the DataBase object to do most of the operations through SQL statements. I’ll talk more about specific Android operations later. If you are interested, you can go to know about Guo Lin’s LitePal, which is convenient for operating SQLite database.