這里寫目錄標題
- 檔案
- 檔案存盤
- 檔案保存
- 檔案讀入
- SharedPreferences
- 得到物件的三種方式
- 存盤資料
- 讀取資料
- CheckBox控制元件
- 記住密碼功能
- SQLite資料庫存盤
- 創建升級
- 添加資料
- 更新資料
- 洗掉資料
- 查詢資料
- LitePal
- 準備
- 配置
- 添加資料
- 更新資料
- 將所有數重設為默認值
- 洗掉資料
- 查詢資料
檔案
檔案存盤
- 不對檔案進行任何格式化處理,適合簡單或二進制檔案
- openFileInput()
以檔案名作為唯一引數,自動到data/data//file目錄下加載檔案,得到FileInputStream物件,通過java流讀出來
檔案保存
public void save(){
//初始化
String data="Data to Save"
FileOutputStream fos=null;
BufferWriter bw=null;
try{
//轉物件,寫進
fos=openFileOutput("data",Context.MODE_PRIVTAE);//(檔案名,模式)
bw=new BufferWriter(new OutputStreamWriter(fos));
//處理例外
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(bw!=null){
bw.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
- 應用(將EditText框里的內容保存)
public class MainActivity extends AppCompatActivity {
EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit=(EditText)findViewById(R.id.edit);
}
protected void onDestory(){
//重寫onDestory(),保證在活動銷毀之前會呼叫
//重寫不僅繼承父類功能,還加上自己的行為save()
super.onDestroy();
String inputText=edit.getText().toString();
save(inputText); //呼叫save方法
}
}
檔案讀入
//用openFileInput()獲取FileInputStream,構建InputStreamReader,再BufferedReader
public String load(){
//初始化
FileInputStream fi=null;
BufferReader br=null;
StringBuilder content=new StringBuilder();
try{
//轉物件
in=openFileInput("data");
br=new BufferedReader(new InputStramReader(in));
//拿到
String line="";
while((line==br.readLine())!=null){
content.append(line);
}
//處理例外
}catch(IOException e){
e.printStackTrace();
}
return content.toString();
}
- 查看存盤:Android Device Monitor ->File Explorer
SharedPreferences
得到物件的三種方式
-
Context. getSharedPreferences(檔案名,MODE_PRIVATE)
-
Activity . getPreferences(MODE_PRIVATE)
- 以
類作為前綴名
- 以
-
PreferenceManger . getDefaultSharedPreferences()
- 靜態方法,以
包作為前綴名,接受Context引數
- 靜態方法,以
存盤資料
- edit()編輯,apply()提交
- putXxx 向SharedPreferences.Editor物件中添加資料,
//MainActivity
protected void onCreate..
...
Button savaData=(Button)findViewById(R.id.save_data);
saveData.setOnClickListener(new View.OnClickListener){
public void onClick(View v){
SharePreferences.Editor editor=getSharePreferences("data",MODE_PRIVATE).edit();
editor.putString("name","Tom");
editor.putInt("age",28);
editor.putBoolean("married",true);
editor.apply();
}
}
讀取資料
- 每一個put方法都對應一個get方法
- 儲存鍵值對,通過得到鍵,得到值
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
...
Button restore=(Button)findViewById(R.id.resore);
View.OnClickListener(new View.OnClickListener(){
public void onClick(View v){
SharedPreferences pref=getPreferences("data",MODE_PRIVATE);
String name= pref.getString("name","");
int age= pref.getInt("age",0);
boolean married=pref.getBoolean("married",true);
Log.d("MainActivity",name);
Log.d("MainActivity","age is"+age);
Log.d("MainActivity","married is"+married);
});
}
CheckBox控制元件
記住密碼功能

//LoginActivity
public class LoginActivity extends AppCompatActivity {
//初始化
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private EditText accountEdit;
private EditText passwordEdit;
private Button login;
private CheckBox rememberPass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login2);
pref= PreferenceManager.getDefaultSharedPreferences(this); //獲取物件
accountEdit=(EditText)findViewById(R.id.account);
passwordEdit=(EditText)findViewById(R.id.password);//獲取密碼,賬號實體
rememberPass=(CheckBox)findViewById(R.id.remember_pass);
login=(Button)findViewById(R.id.login);
boolean isRemember=pref.getBoolean("remember_password",false);
//把賬號密碼都設定到文本框中
if(isRemember){
//賬號密碼初始化
String account=pref.getString("account","");
String password=pref.getString("password","");
accountEdit.setText(account);
passwordEdit.setText(password);
rememberPass.setChecked(true);
}
login.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
String account = accountEdit.getText().toString(); //getText() toString()功能
String password = passwordEdit.getText().toString();
if (account.equals("Alice") && password.equals("12345678")) {
editor=pref.edit();
if(rememberPass.isChecked()){ //檢查復選框是否被選中
editor.putBoolean("remember_password",true); //儲存下來
editor.putString("account",account);
editor.putString("password",password);
}else{
editor.clear(); //沒有被選中,SharedPreferences中資料清除
}
editor.apply();//提交
Intent intent = new Intent(LoginActivity.this, MainActivity.class);//Intent,登錄成功,就跳轉到MainActivity
startActivity(intent);
finish();
} else {
Toast.makeText(LoginActivity.this, "account or password is invalid", Toast.LENGTH_SHORT).show();
}
}
});
}
}
SQLite資料庫存盤
- 特點
速度快,占用資源少,適合在移動設備上使用
可無需用戶密碼賬戶,支持標準SQL,ACID事務 - getReadableDatabase() ,
getWritableDatabase()有創建或打開現有資料庫功能,磁盤已滿時,只能用只讀的方式打開資料庫
創建升級
- 創建幫助類,重寫 onUpgrade() onCreate()
//MyDataBaseHelper類
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK="create table Book("
+"id integer primary key autoincrement,"//將id設為主鍵,用autoincrement實作id列自增長
+"author text," //text文本型別
+"price real," //real浮點型
+"pages integer" //integer整型
+"name text)"; //blob二進制型
public static final String CREATE_CATEGORY="create table category("+
"id integer primary key autoincrement,"
+"name text,"
+"code integer)";
private Context myContext;
//四個引數:背景關系,資料庫名,(查詢資料時回傳自定義Cursor)null,版本號
public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){
super(context,name,factory,version);
myContext=context;
}
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_BOOK); //execSQL執行建表陳述句
db.execSQL(CREATE_CATEGORY);
Toast.makeText(myContext,"Create Successful~!",Toast.LENGTH_SHORT).show();
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");//DROP陳述句,如果存在,就先刪掉
onCreate(db);
}
}
添加資料
//MainActivity
protected void onCreate...
...
//dbHelper=new MyDatabaseHelper(this,"BookSore.db",null,2);//創建時
dbHelper=new MyDatabaseHelper(this,"BookStore.db",null,2);//比創建是資料庫版本號高即可運行更新流程
//MainActivity
protected void onCreate...
...
Button addData=(Button)findViewById(R.id.add_data);
addData.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
//獲取SQL物件
SQLiteDatabase db=dbHelper.getWritableDatabase();
//使用ContentValues對要添加的資料進行組裝
ContentValues values=new ContentValues();
values.put("name","Micheal");
value.put("page",455);
db.insert("Book",null,values);//添加陳述句
values.clear();
//前面創建表時,將id列設為自增長,無需再手動賦值
//輸入SQL查詢陳述句--select*from Book
}
更新資料
db.update("Book",values,"name=?",new String[]{"Karl"});
洗掉資料
public void onClick(View v){
SQLiteDatabase db=dbHelper.getWritableDatabase();
db.detele("Book","page>?",new String[]{"500"});
}
查詢資料
public void onClick(View v){
SQLiteDatabase db=dbHelper.getWritableDatabase();
//查詢Book表中所有資料
Cursor cursor=db.query("Book",null,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
//遍歷Cursor物件,取出資料并列印
String name=cursor.getName(cursor.getColumnIndex("name"));
Int age=cursor.getName(cursor.getColumnIndex("age"));
Lod.d("MainActivity","book name"+name);
}while(cursor.moveToNext());
}
cursor.close();
}
- 除查詢資料呼叫的是rawQuery()方法,其他操作都是execSQL
LitePal
準備
配置
- 環境
//app/build.gradle
dependencies{
...
implementation 'org.litepal.guolindev:core:3.1.1'//3.1.1為Litepal最新版本號
}
- 檔案
在app/scr/main下創建assets目錄,再建litepal.xml檔案,可切換project模式,New->Folder->assets即可

<?xml version="1.0" encoding="utf-8"?>
<litepal>
<dbname value="Record"></dbname>
<version value="1"></version>
<list>
<mapping class="com.example.uichat.record"></mapping>
</list>
</litepal>
- AndroidManifest.xml
<application
android:name="org.litepal.LitePalApplication"
...
添加資料
Button updateData=(Button)findViewById(R.id.update_button);
updaateData.swtOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Book book=new Book();
book.setName("The Lost Symbol");
book.setAuthor("Amy");//添加資料
...
book.save();
//book.setAuthor("Judy");//更新
//book.save();
}
})
更新資料
Book book=new Book();//實體
book.setName("The Lost Symbol");//要更新的部分
book.setAuthor("Amy");
book.updateAll("press =? and prices=?","Anthor",43);//設定條件,滿足則更新,不設定將會更新所有
將所有數重設為默認值
Book book=new Book();
book.setToDefault("pages");//將所有書頁數設為默認值
book.uodateAll();.
洗掉資料
public void onnClick(View v){
DataSupport.deteleAll(Book.class,"price<?",15);
}
查詢資料
public void onClick(View v){
List<Book> books=DataSupport.findAll(Book.class);
for(Book book:books){
Log.d("MainActivity","the name of book is"+book.getName());
...
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/292526.html
標籤:其他
上一篇:2021-08-07
