[Notes] Anroid learning basic common persistence technology use

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/A1344714150/article/details/100155915

File Storage

The stored data to a file

Core code:

save(){ 
String data = "Data to save";
FileOutputStream out = null; 
BufferedWriter writer = null; 
try{ 
//通过openFileOutput()方法获取FileOutputStream的实例, 
//第一个参数是文件名,第二个参数是操作模式 
out = openFileOutput("data",Context.MODE_PRIVATE); 
writer = new BufferedWriter(new OutputStreamWriter(out)); 
writer.write(data);
}catch(IOException e){
 ... 
}finally{
 try{
 if(writer!=null){ 
 writer.close(); 
 } 
 }catch(IOException e){ 
 ... 
 }
 }
 }

Operating mode Meaning

1 Context.MODE_PRIVATE: If the file already exists, the written content will overwrite the original content

2 Context.MODE_APPEND: If the file already exists, the written content will be added on the basis of the original content

File storage location

/data/data/<packagename>/files/

Open

With Android Device Monitor tool (Tools-> Android-> Android Device Monitor), locate the file,

Export to a computer, use Notepad to open to view.

 

Reading data from a file

Core code:

load(){ 
FileInputStream in = null; 
BufferedReader reader = null; 
StringBuilder content = new StringBuilder(); 
try{ 
//通过openFileInput()方法获取FileInputStream的实例, 
//传入的参数是文件名 
in = openFileInput("data"); 
reader = new BufferedReader(new InputStreamReader(in)); 
String line = ""; 
while((line = reader.readLine())!=null){ 
content.append(line);
} 
}catch(IOException e){
 ... 
}finally{ 
if(reader!=null){ 
try{ 
read.close(); 
}catch(IOException e){
 ... 
}
}
}
return content.toString();
}

 

SharedPreferens storage

Objects are three ways to get SharedPreferences

1 context class getSharedPreferences () method

2 Activity class getPreferences () method

3 PreferenceManager class getDefaultSharedPreferences () method

To store the data file SharedPreferences

Core code:

onClick(){ 
//存储数据需要先获取SharedPreferences.Editor实例,接着添加数据, 
//最后使用apply()进行提交 
SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit(); editor.putString("name","Tom"); 
editor.putInt("age",28); 
editor.putBoolean("married",false); 
editor.apply();
}

 

Reading data from a file SharedPreferences

Core code:

onClick(){ 
//读取数据不需要获取
SharedPreferences.Editor SharedPreferences pref =
getSharedPreferences("data",MODE_PRIVATE); 
//第一个参数是键,第二个参数是默认值(如果没找到键对应的值) 
String name = pref.getString("name",""); 
int age = pref.getInt("age",0); 
boolean married = pref.getBoolean("married",false); 
Log.d("MainActivity","name is " + name);
 ... 
}

File storage location

/data/data/<package name>/shared_prefs/

Open

With Android Device Monitor tool (Tools-> Android-> Android Device Monitor), locate the file,

Export to a computer, use Notepad to open to view.

 

SQLite database storage

Create a database

Handwriting help SQLiteOpenHelper class to inherit the abstract class:

class MyDatabaseHelper extends SQLiteOpenHelper{ 
String create_book = "建表SQL语句"; 
Context mContext; 
//构造方法的第一个参数是上下文环境,第二个参数是数据库名, 
//第三个参数允许我们查询数据时返回自定义的Cursor,一般传入null, 
//第四个参数表示当前数据库的版本号 
public MyDatabaseHelper(Context context,...,...,...){
 super(...,...,...,...); 
 mContext = context; 
} 
onCreate(){ 
//执行SQL语句 
db.execSQL(create_book); 
} 
onUpgrade(){
 ... 
}
}

Main Code Method:

onCreate(){ 
dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,1); 
onClick(){ 
//不存在数据库时,先执行帮助类里的onCreate()方法创建数据库 
dbHelper.getWriteableDatabase(); 
}
}

File storage location

/data/data/<package name>/databases/

Open (db suffix)

Use adb shell tool (stored in the platform-tools directory sdk's).

Adb shell configuration tool

In the home path editing .bash file, the platform-tools directory can be configured into it.

Upgrade the database

Core code:

class MyDatabaseHelper extends SQLiteOpenHelper{ 
//当重新指定的数据库的版本号大于之前的数据库的版本号时, 
//将执行onUpgrade()方法; 
onUpgrade(){ 
db.execSQL("drop table if exists Book"); 
db.execSQL("drop table if exists Book"); 
onCreate(db); 
} 
}

adding data

Core code:

onClick(){ 
SQLiteDatabase db = dbHelper.getWriteableDatabase();
ContentValues values = new ContentValues(); 
//添加第一条数据 
values.put("name","The Da Vinci Code"); 
values.put("author","Dan Brown"); 
values.put("price",16.96); 
values.put("pages",454); 
//第一个参数是表名,第二个参数用于对可为空的字段自动赋值null,直接传入null 
//即可,第三个参数是一个ContentValues对象 
db.insert("Book",null,values);
values.clear(); 
//添加第二条数据 
...... 
}

update data

Core code:

onClick(){ 
SQLiteDatabase db = dbHelper.getWritableDatabase(); 
ContentValues values = new ContentValues(); 
values.put("price",10.99); 
//第三个参数对应SQL的where部分,?是占位符,第四个参数通过字符串数组为 
//第三个参数中的每个占位符指定相应的内容 
db.update("Book",values,"name = ?",new String[]{"The Da Vinci Code"}); 
}

delete data

Core code:

onClick(){ 
SQLiteDatabase db = dbHelper.getWritableDatabase(); 
//第二个参数和第三个参数对应SQL的where部分,如果不指定则删除所有行 
db.delete("Book","pages > ?",new String[]{"500"}); 
}

Query data

Core code:

onClick(){ 
SQLiteDatabase db = dbHelper.getWritableDatabase(); 
//第一个参数指查询的表名,第二个参数指查询的列名,第三个参数指where的约束条件 
//第四个参数为where中的占位符提供具体的值,第五个参数指需要group by的列, 
//第六个参数对group by后的结果进一步约束,第七个参数指定查询结果的排序方式 
Cursor cursor = db.query("Book",null,null,null,null,null,null); 
if(cursor.moveToFirst()){ 
do{ 
String name = cursor.getString(cursor.getColumnIndex("name")); 
String author = cursor.getString(cursor.getColumnIndex("author")); 
int pages = cursor.getInt(cursor.getColumnIndex("pages")); 
double price = cursor.getDouble(cursor.getColumnIndex("price")); 
...... 
}
} 
}

 

Database operations using LitePal

Configuration LitePal

First edit the app / build.gradle file, add the following to the closure of dependencies:

dependencies{
 ... 
compile 'org.litepal.android:core:1.4.1' 
}

Next litepal.xml configuration file, edit the file litepal.xml as follows:

<?xml version="1.0" encoding="utf-8"?> 
<litepal> 
//dbname指定数据库名 
<dbname value="BookStore"></dbname> 
//version指定数据库版本号 
<version value="1"></version> 
//list指定所有的映射模型 
<list> </list> 
</litepal>

Finally, configure the look LitePalApplication, modify AndroidMainifest.xml as follows:

<manifest> 
//这里将项目的application配置为org.litepal.LitePalApplication,这样才能让 
//LitePal的所有功能都可以正常工作 
<application android:name="org.litepal.LitePalApplication" ...> </application> 
</manifest>

Creating databases and upgrade

Create a JavaBean:

public class Book{ 
private int id; private String author; 
private double price; 
private int pages; 
private String name; 
public int getId(){ 
return id;
} 
public void setId(int id){
this.id = id; 
} 
... 
}

Book class you need to add to the list of the mapping model, modify the code litepal.xml as follows:

<?xml version="1.0" encoding="utf-8"?> 
<litepal> 
<dbname value="BookStore"></dbname> 
<version value="1"></version> 
<list> 
//添加映射,注意一定要使用完整的类名 
<mapping class="com.example.litepaltest.Book">
</mapping> 
</list> 
</litepal>

Modify MainActivity as follows:

onClick(){ 
//调用LitePal.getDatabase()方法是最简单的数据库操作 
LitePal.getDatabase(); 
}

After completion of change want to change something, just remember the version number plus 1, modify litepal.xml as follows:

<?xml version="1.0" encoding="utf-8"?> 
<litepal> 
<dbname value="BookStore"></dbname> 
<version value="2"></version> 
<list> 
//添加映射,注意一定要使用完整的类名 
<mapping class="com.example.litepaltest.Book"></mapping> 
<mapping class="com.example.litepaltest.Category"></mapping> 
</list> 
</litepal>

Rerun the program, we found that successful changes, and LitePal also automatically help us retain all previous data in the table.

Adding data using LitePal

When CRUD operations, JavaBean need to inherit from DataSupport categories:

class Book extends DataSupport{ 
... 
}

Data was then added to the Book table, modifying MainActivity follows:

onClick(){ 
Book book = new Book(); 
book.setName("The Da Vinci Code"); 
book.setAuthor("Dan Brown"); 
book.setPages(454); 
book.setPrice(16.96); 
book.setPress("Unknow"); 
//调用save()方法完成数据添加操作 
book.save(); 
}

Use LitePal update data

Only two cases model.isSaved () method returns true.

The first case is made that call model.save () method to add data, then model will be considered an object stored.

The second case is a model provided by LitePal query API to check out, because it is found from the database object, so the object will be considered to be stored.

 

The first way to update the core code:

onClick(){ 
Book book = new Book(); 
book.setName("The Da Vinci Code"); 
book.setAuthor("Dan Brown"); 
book.setPages(454); 
book.setPrice(16.96); 
book.setPress("Unknow"); 
book.save(); 
book.setPrice(10.99); 
book.save();
}

The second way to update the core code:

onClick(){ 
Book book = new Book(); 
book.setPrice(14.95); 
book.setPress("Anchor"); 
//后面两个参数对应前面的占位符 
book.updateAll("name = ? and author = ?","The Lost Symbol","DanBrown"); 
}

If you want to update the value of a field to the default value, the above operation is not acceptable.

May be used SetToDefault () method, and pass the appropriate column names can be achieved, as follows:

Book book = new Book(); 
book.setDefaultTo("pages"); 
book.updateAll();

Use LitePal delete data

There are two ways to use LitePal delete data.

The first way the core code:

Book book = new Book(); 
book.setName("The Da Vinci Code"); 
book.setAuthor("Dan Brown"); 
book.save(); 
//直接调用已存储对象的delete方法即可删除数据 
book.delete();

The second way the core code:

onClick(){ 
DataSupport.deleteAll(Book.class,"price < ?","15");
}

Use LitePal query data

The core code to achieve:

onClick(){ 
//查询表中所有数据 
List<Book> books = DataSupport.findAll(Book.class); 
//查询表中第一条数据 
Book firstBook = DataSupport.findFirst(Book.class); 
//查询表中最后一条数据 
Book lastBook = DataSupport.findLast(Book.class); 
//连缀查询select(),指定查询列名 
List<Book> books = DataSupport.select("name","author").find(Book.class); 
//连缀查询where(),指定查询的约束条件 
List<Book> books = DataSupport.where("pages > ?","400").find(Book.class); 
//连缀查询order(),指定结果的排序方式 
List<Book> books = DataSupport.order("price desc").find(Book.class); 
//连缀查询limit(),指定查询结果的数量 
List<Book> books = DataSupport.limit(3).find(Book.class); 
//连缀查询offset(),指定查询结果的偏移量(查询第2,3,4条记录) 
List<Book> books = DataSupport.limit(3).offset(1).find(Book.class); 
//定制查询 
List<Book> books = DataSupport.select("name","author","pages") .where("pages > ?","400").order("pages").limit(10).offset(10) .find(Book.class); 
//如果实在有上述API无法满足的情况,使用原生SQL查询 
Cursor c = DataSupport.findBySQL("select * from Book where pages > ? and price < ?","400","20"); 
}

 

 

Guess you like

Origin blog.csdn.net/A1344714150/article/details/100155915