目录
6.1简介
android提供三种存储方式:
(1)文件存储
(2)SharedPreferences存储
(3)数据库存储
6.2文件存储
public class MainActivity extends AppCompatActivity {
private EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.text);
String inputText = load();
if(!TextUtils.isEmpty(inputText)){
editText.setText(inputText);
editText.setSelection(inputText.length());
Toast.makeText(this,"Successed",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
String inputText = editText.getText().toString();
save(inputText);
}
public void save(String inputText){
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(writer!=null)
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String load(){
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = openFileInput("data");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while((line = reader.readLine()) != null){
content.append(line);//使用StringBuilder更快
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(reader != null){
try{
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content.toString();
}
}
指定文件名时不能包含路径,文件统一保存在data/data/<packagename>/files目录下
文件操作模式:MODE_PRIVATE(默认,覆盖文件内容)/MODE_APPEND(追加到文件尾,文件不存在则创建该文件)
setSelection(inputText.length()):输入光标移动到文本末尾处
TextUtils.isEmpty(String):当传入的字符串等于null或者等于空字符串时,该方法返回true。
6.3SharedPersistences存储
存储数据:
(1)得到SharedPersistences对象(有三种方法):
Context类中的getSharedPreferences():第一个参数指定文件名,没有就创建。文件存放在/data/data/<package name>/shared_prefs目录下。第二个参数用于指定操作模式:目前只有MODE_PRIVATE一种,表示只有当前程序才可以对SharedPersistences文件进行读写。
Activity类中的getPreferences():默认文件为当前活动类名,参数为操作模式。
PreferenceManager类中的getDefaultSharedPreferences():静态方法,接受Context为参数,以当前应用程序的包名来命名SharedPersistences文件名。
(2)调用edit()方法获取Editor对象
(3)put()方法存储数据
(4)apply()提交数据
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
Button button2 = (Button) findViewById(R.id.button_back);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();//获得Editor对象
editor.putString("name","Tom");//输入数据
editor.putInt("age",28);
editor.putBoolean("married",false);
editor.apply();//提交
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences preferences = getSharedPreferences("data",MODE_PRIVATE);
String name = preferences.getString("name","");
int age = preferences.getInt("age",0);
boolean married = preferences.getBoolean("married",false);
Log.d("MainActivity","name is "+name);
Log.d("MainActivity","age is "+age);
Log.d("MainActivity","merried is "+married);
}
});
}
6.4SQLite数据库存储
6.4.1创建数据库
SQLiteOpenHelper:抽象类,用于创建或者升级数据库。包含两个抽象方法getReadableDatabase(),getWritableDatabase()。
getReadableDatabase():创建或打开一个数据库,并返回一个可对数据库进行操作的对象。当数据不可写时,返回的对象以只读的方式打开数据库。
getWritableDatabase():创建或打开一个数据库,并返回一个可对数据库进行操作的对象。当数据库不可写入时,抛出异常。
SQLiteOpenHelper(a,b,c,d):a,Context;b,数据库名;c,允许查询数据时返回一个自定义的Cursor;d,当前数据库版本号,用于升级;
数据库文件存放在data/data/<package name>/database目录下
public class MyDatabasehelper extends SQLiteOpenHelper {
Context myContext;
public static final String CREATE_BOOK = "create table Book (" +
"id integer primary key autoincrement," +
"author text," +
"price real" +
"name text)";
public MyDatabasehelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
this.myContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
Toast.makeText(myContext,"Create succeeded",Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public class MainActivity extends AppCompatActivity {
private MyDatabasehelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper = new MyDatabasehelper(this,"Bookstore.db",null,1);
Button button = (Button) findViewById(R.id.create_d);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
helper.getWritableDatabase();
}
});
}
}
adb shell 查看具体的表
sqlite3 + 数据库名.db//进入数据库
.table//查看数据库内的表
.schema//查看建表语句
6.4.2升级数据库
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");
onCreate(db);
}
helper = new MyDatabasehelper(this,"Bookstore.db",null,2);
将已经重复存在的表删去,修改版本号。
6.4.3数据库操作
添加数据
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name","The Da Vinci Code");
values.put("author","Dan Brown");
values.put("pages",454);
values.put("price",16.96);
db.insert("Book",null,values);//插入数据
db.execSQL("insert into Book (name,author,pages,price) values (?,?,?,?)",new String[]{"The Da Vinci Code","Dan Brown","454","16.96"});
insert():第一个参数,表名;第二个参数,对于可为null的值,自动赋值为null;第三个参数,ContentValues对象,用于存储待插入的数据。
更新数据
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price",10.99);
db.update("Book",values,"name=?",new String[]{"The Da Vinci Code"});
db.execSQL("update Book set price = ? where name=?",new String[]{"10.99","The Da Vinci Code"}});
update():第一个参数,表名;第二个参数,ContentValues对象,存储待修改的数据;第三、四个参数,确定要修改的位置,默认为所有所有行。
删除数据
SQLiteDatabase db = helper.getWritableDatabase();
db.delete("Book","pages > ?",new String[]{"500"});
db.execSQL("delete from Book where pages >?",new String[]{"500"});
查找数据
SQLiteDatabase db = helper.getWritableDatabase();
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"));
Log.d("MainActivity","book name is "+name);
Log.d("MainActivity","book author is "+author);
Log.d("MainActivity","book pages is "+pages);
Log.d("MainActivity","book price is "+pages);
}while (cursor.moveToNext());
}
cursor.close();
db.execSQL("select * from Book",null});
Cursor对象保存查询到的数据
query(table,columns,selection,selectionArgs,groupBy,having,orderBy);后六个参数可设置为默认值
6.4LitePal
(1)配置LitePal并创建数据库:
引用库:dependencies{compiler 'org.litepal.android:core:2.0.0'}
创建目录:assets;创建litepal.xml文件
<?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>
修改AndroidManifest.xml
改为<application android:name="org.litepal.LitePalApplication"></application>
(2)增删改查:阅读LitePal官方文档。使用最新的方法。