Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of Storage instance in Android

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this article, the editor introduces "Storage instance Analysis in Android" in detail, with detailed content, clear steps and proper handling of details. I hope this article "Storage instance Analysis in Android" can help you solve your doubts.

1. Stored inside App

The simplest one. In the process of trying, I found that many folders in the phone do not have permission to read or write. We can store the files we need to write to the files folder in App, and of course we have permission to read and write files in the entire App.

You can get a file object through API, where this is the MainActivity class

/ / get the files path / data/data/top.woodwhale.qqlogin/filesFile filesDir = this.getFilesDir () under the current package; then you can write to the file via the file output stream: File filesFile = new File (filesDir, "info.txt"); boolean flag = (filesFile.exists () | | filesFile.createNewFile ()); FileOutputStream fos = new FileOutputStream (file); fos.write ((ac+ "* *" + pwd) .getBytes (StandardCharsets.UTF_8)); fos.close ()

Write successful:

Of course, since we all have permissions in this App, all directories can be written:

/ / write to the place where you have permission to write File file = new File ("/ data/data/top.woodwhale.qqlogin/info.txt"); 2. SD card external storage

Although many mobile phones no longer support SD cards, there are still tablets to use.

Directly release an Activity class, which calls nvironment.getExternalStorageDirectory (); the method class gets an SD card file object, using Formatter.formatFileSize (this,externalStorageDirectory.getFreeSpace ()); the conversion in the Formatter class converts the long type to the size type, while calling the getFreeSpace () method of the SD card file object to get the remaining space in the card, and then write to the path in the externalStorageDirectory.getPath () card

Public class SdcardActivity extends Activity {private Button btn; public static String TAG = "SdcardActivity"; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_sc_card_rw); btn = this.findViewById (R.id.bt_sdw); btn.setOnClickListener (view-> {File externalStorageDirectory = Environment.getExternalStorageDirectory () Log.d (TAG, "SD card path is:" + externalStorageDirectory.getPath ()); Log.d (TAG, "SD card remaining space is" + Formatter.formatFileSize (this,externalStorageDirectory.getFreeSpace (); File file = new File (externalStorageDirectory, "love.txt"); try {boolean flag = file.exists () | file.createNewFile () If (flag) {FileOutputStream fos = new FileOutputStream (file); fos.write ("woodwhale love sheepbotany" .getBytes (StandardCharsets.UTF_8)); fos.close ();} catch (Exception e) {e.printStackTrace ();}}) }} however, before that, we need a read and write permission for the SD card. We configure the following ses-permission in AndrodiManifest.xml. Finally, we see the following result in our SD card, which proves that the write is successful:

3. SharedPreferences storage

SharedPreferences is a class under android. Its function is to record preferences and form a xml file.

We can use SharedPreferences to store some information.

For example, the common one:

After we check it, the app is still checked when we open it again.

So how does this happen?

Generate the above layout through xml

We assign the selection box Switch to a variable in the activity class, add an OnCheckedChangeListener to it, and then use SharedPreferences to set preferences. The overall code is as follows: package top.woodwhale.qqlogin;import android.app.Activity;import android.content.SharedPreferences;import android.os.Bundle;import android.util.Log;import android.widget.CompoundButton;import android.widget.Switch;import androidx.annotation.Nullable;public class PreferenceDemoActivity extends Activity {private Switch sw; public static String TAG = "PreferenceDemoActivity" @ Override protected void onCreate (@ Nullable Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_pre_demo); sw = (Switch) this.findViewById (R.id.sw_source); SharedPreferences settingInfo = this.getSharedPreferences ("settingInfo", MODE_PRIVATE); SharedPreferences.Editor edit = settingInfo.edit (); sw.setOnCheckedChangeListener (new MyListener (edit)) Boolean state = settingInfo.getBoolean ("state", true); Log.d (TAG, "STATE==" + state); sw.setChecked (state);}} / / listener class MyListener implements CompoundButton.OnCheckedChangeListener {SharedPreferences.Editor editor; public MyListener (SharedPreferences.Editor editor) {this.editor = editor } @ Override public void onCheckedChanged (CompoundButton compoundButton, boolean b) {Log.d (PreferenceDemoActivity.TAG, "current state:" + b); editor.putBoolean ("state", b); / / data type to be saved editor.commit (); / / Save data}} where the function of editor is to save data

Second, in order to see our configuration every time we open App, set the check box of the switch box by reading the preference configuration file

In this way, you can synchronize the check box of your preferences!

Finally, we can see the preference xml file we wrote inside the phone, which is also stored in App.

4. Use SQLite database to store

Android equipment comes with SQLite database, if you have mastered mysql, then SQLite is very easy to use, not to mention providing a very simple API, even if you write it yourself is easier than JDBC!

First of all, we do not apply the API provided to achieve an add, delete, change and search!

4.1 complete a BaseDao class by yourself

The BaseDao class is originally used to connect to the database and other basics, and the specific additions, deletions, modifications and queries should be implemented in the service layer, but in order to test here, we write the crud method into the BaseDao class and encapsulate it. The specific structure is as follows:

The first is the Constants class, which is a constant class with our database name, version number, and table name.

Public class Constants {public static final String DATABASE_NAME = "woodwhale.db"; public static final int VERSION_CODE = 1; public static final String TABLE_NAME = "user";}

The second is the DatabaseHelper class, which inherits the SQLiteOpenHelper class, which is used to open the database. The onCreate method is the callback when the database is created, and the callback when the onUpgrade method upgrades the data. We write a version number in the Constans class. Dad can add new functions to each upgrade, which can be written in the onUpgrade method and implemented through switch. However, it should be noted that the upgrade can only increase the version number, not downgrade, otherwise an error will be reported!

Package top.woodwhale.qqlogin.SQLite.utils;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;public class DatabaseHelper extends SQLiteOpenHelper {public static String TAG = "DatabaseHelper"; / * * @ param context context * / public DatabaseHelper (Context context) {super (context, Constants.DATABASE_NAME, null, Constants.VERSION_CODE) } @ Override public void onCreate (SQLiteDatabase sqLiteDatabase) {/ / callback Log.d (TAG, "create database"); String sql = "create table" + Constants.TABLE_NAME + "(id integer,name varchar,age integer)"; sqLiteDatabase.execSQL (sql) } @ Override public void onUpgrade (SQLiteDatabase sqLiteDatabase, int I, int i1) {/ / upgrade database callback Log.d (TAG, "upgrade database!") ; String sql = null; switch (I) {case 1: sql = "alter table" + Constants.TABLE_NAME + "add phone integer"; sqLiteDatabase.execSQL (sql); break; case 2: sql = "alter table" + Constants.TABLE_NAME + "add address varchar"; sqLiteDatabase.execSQL (sql) Break;}

Finally, we encapsulated the database BaseDao class, which realized the addition, deletion, modification and query through statements.

Package top.woodwhale.qqlogin.SQLite.dao;import android.annotation.SuppressLint;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.util.Log;import top.woodwhale.qqlogin.SQLite.utils.Constants;import top.woodwhale.qqlogin.SQLite.utils.DatabaseHelper;// BaseDao class public class BaseDao {private final DatabaseHelper dbh; private SQLiteDatabase db; public static String TAG = "BaseDao"; public BaseDao (Context context) {dbh = new DatabaseHelper (context) } / / add public void add (int id, String name, int age) {db = dbh.getWritableDatabase (); String sql = "insert into" + Constants.TABLE_NAME + "(id,name,age) values (?)"; Object [] params = new Object [] {id,name,age}; db.execSQL (sql,params); db.close () } / / delete public void free (int id) {db = dbh.getWritableDatabase (); String sql = "delete from" + Constants.TABLE_NAME + "where id=?"; Object [] params = new Object [] {id}; db.execSQL (sql,params); db.close ();} / change public void edit (int id, int age) {db = dbh.getWritableDatabase () String sql = "update" + Constants.TABLE_NAME + "set age =? Where id =? "; Object [] params = new Object [] {age,id}; db.execSQL (sql,params); db.close ();} / check @ SuppressLint (" Range ") public void show (int id) {db = dbh.getReadableDatabase (); String sql =" select * from "+ Constants.TABLE_NAME +" where id =? " String [] params = new String [] {String.valueOf (id)}; Cursor cursor = db.rawQuery (sql, params); while (cursor.moveToNext ()) {String name = cursor.getString (cursor.getColumnIndex ("name"); Log.d (TAG, "name = =" + name); int age = cursor.getInt (cursor.getColumnIndex ("age")) Log.d (TAG, "age = =" + age);} cursor.close (); db.close ();}}

Then we tested it under the AndroidTest package

Package top.woodwhale.qqlogin;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.util.Log;import androidx.test.platform.app.InstrumentationRegistry;import androidx.test.ext.junit.runners.AndroidJUnit4;import org.junit.Test;import org.junit.runner.RunWith;import static org.junit.Assert.*;import top.woodwhale.qqlogin.SQLite.dao.BaseDao;import top.woodwhale.qqlogin.SQLite.utils.DatabaseHelper;/** * Instrumented test, which will execute on an Android device. * * @ see Testing documentation * / @ RunWith (AndroidJUnit4.class) public class ExampleInstrumentedTest {public static final String TAG = "ExampleInstrumentedTest"; public static final Context appContext = InstrumentationRegistry.getInstrumentation (). GetTargetContext ();; public static final BaseDao dao = new BaseDao (appContext);; @ Test public void useAppContext () {/ / Context of the app under test. AssertEquals ("top.woodwhale.qqlogin", appContext.getPackageName ());} @ Test public void testCreate () {DatabaseHelper dbh = new DatabaseHelper (appContext); SQLiteDatabase writableDatabase = dbh.getWritableDatabase (); Log.d (TAG, writableDatabase.getPath ());} @ Test public void testAdd () {dao.add (1, "woodwhale", 19); dao.add (2, "sheepbotany", 21) } @ Test public void testFree () {dao.free (1);} @ Test public void testEdit () {dao.edit (1Magne3);} @ Test public void testShow () {dao.show (1);}}

All the additions, deletions, modifications and queries are successful, as shown in the figure:

Since only queries have log echoes, log appears in the show method after logcat

4.2 API processing written by Google

Then using the addition, deletion, modification and query api written by Google can avoid the format problems and syntax errors of our sql statements.

After testing, the following code has no problem (in the BaseDao class)

/ add public void addByAPI (int id, String name, int age) {ContentValues contentValues = new ContentValues (); contentValues.put ("id", id); contentValues.put ("name", name); contentValues.put ("age", age) using API; db = dbh.getWritableDatabase (); db.insert (Constants.TABLE_NAME,null,contentValues); db.close () } / / delete public void freeByAPI (int id) {db = dbh.getWritableDatabase (); db.delete (Constants.TABLE_NAME, "id =?", new String [] {String.valueOf (id)}); db.close (); Log.d (TAG, "API deleted successfully!") ;} / / modify public void editByAPI (int id, String name, Integer age) {ContentValues contentValues = new ContentValues (); if (name! = null) {contentValues.put ("name", name);} if (age! = null) {contentValues.put ("age", age);} db = dbh.getWritableDatabase () Db.update (Constants.TABLE_NAME,contentValues, "id =?", new String [] {String.valueOf (id)}); db.close ();} / / query public void showByAPI (int id) {db = dbh.getReadableDatabase () Cursor cursor = db.query (false, Constants.TABLE_NAME, new String [] {"id", "name", "age"}, "id =?", new String [] {String.valueOf (id)}, "id", null, null, null); while (cursor.moveToNext ()) {int ID = cursor.getInt (0); Log.d (TAG, "ID = =" + ID) String name = cursor.getString (1); Log.d (TAG, "name = =" + name); int age = cursor.getInt (2); Log.d (TAG, "age = =" + age);} cursor.close (); db.close ();} 4.3 transaction usage

Use db.beginTransaction (); db.setTransactionSuccessful (); db.endTransaction (); three methods for transaction processing.

A simple test class

/ / Test a database transaction @ Test public void testTransaction () {DatabaseHelper dbh = new DatabaseHelper (appContext); SQLiteDatabase db = dbh.getWritableDatabase (); db.beginTransaction (); Log.d (TAG, "things open!") ; try {db.execSQL ("update" + Constants.TABLE_NAME + "set age = 114where id = 1"); int I = 10 / 0; db.execSQL ("update" + Constants.TABLE_NAME + "set age = 114where id = 2"); db.setTransactionSuccessful (); Log.d (TAG, "things succeed!") ;} catch (Exception e) {e.printStackTrace ();} finally {db.endTransaction (); db.close (); Log.d (TAG, "things are closed!") ;} dao.showByAPI (1); dao.showByAPI (2);}

Look at logcat, first of all, enter the thing to open, and then the program enters the try, because divided by a 0 so the error is reported, after catching the exception, you enter the finally to close the transaction, you can find that all the information in our sql has been rolled back and has not changed.

If we delete int I = 10 / 0; for a try, we can see that things are executed successfully.

It is worth noting that after things are opened, only the current db object can execute the sql statement, and it is impossible to add, delete, modify and check using the methods in the Dao class, because these resulting db objects are locked!

After reading this, the article "Storage instance Analysis in Android" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report