1 Android数据存储方式
1.1 SharedPreferences存储
说明
相关API
public class SpActivity extends Activity {
private EditText et_sp_key;
private EditText et_sp_value;
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sp);
et_sp_key = (EditText) findViewById(R.id.et_sp_key);
et_sp_value = (EditText) findViewById(R.id.et_sp_value);
//1. 得到sp对象
sp = getSharedPreferences("atguigu", Context.MODE_PRIVATE);
}
public void save(View v) {
//2. 得到editor对象
Editor edit = sp.edit();
//3. 得到输入的key/value
String key = et_sp_key.getText().toString();
String value = et_sp_value.getText().toString();
//4. 使用editor保存key-value
edit.putString(key, value).commit();
//5. 提示
Toast.makeText(this, "保存完成!", 0).show();
}
public void read(View v) {
//1. 得到输入的key
String key = et_sp_key.getText().toString();
//2. 根据key读取对应的value
String value = sp.getString(key, null);
//3. 显示
if(value==null) {
Toast.makeText(this, "没有找到对应的value", 0).show();
} else {
et_sp_value.setText(value);
}
}
}
1.2 手机内部file存储
说明
相关API
代码:
package com.atguigu.l04_datastorage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
/**
* 测试手机内部文件存储
*
*
*/
public class IFActivity extends Activity {
private ImageView iv_if;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_if);
iv_if = (ImageView) findViewById(R.id.iv_if);
}
public void save(View v) throws IOException {
//1. 得到InputStream-->读取assets下的logo.png
//得到AssetManager
AssetManager manager = getAssets();
//读取文件
InputStream is = manager.open("logo.png");
//2. 得到OutputStream-->/data/data/packageName/files/logo.png
FileOutputStream fos = openFileOutput("logo.png", Context.MODE_PRIVATE);
//3. 边读边写
byte[] buffer = new byte[1024];
int len = -1;
while((len=is.read(buffer))!=-1) {
fos.write(buffer, 0, len);
}
fos.close();
is.close();
//4. 提示
Toast.makeText(this, "保存完成", 0).show();
}
public void read(View v) {// /data/data/packageName/files/logo.png
//1. 得到图片文件的路径
// /data/data/packageName/files
String filesPath = getFilesDir().getAbsolutePath();
String imagePath = filesPath+"/logo.png";
//2. 读取加载图片文件得到bitmap对象
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
//3. 将其设置到imageView中显示
iv_if.setImageBitmap(bitmap);
}
}
1.3 SD卡外部file存储
说明
相关API
代码
package com.atguigu.l04_datastorage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
/**
* 测试手机外部文件存储
*
*/
public class OFActivity extends Activity {
private EditText et_of_name;
private EditText et_of_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_of);
et_of_name = (EditText) findViewById(R.id.et_of_name);
et_of_content = (EditText) findViewById(R.id.et_of_content);
}
public void save(View v) throws IOException {
//1. 判断sd卡状态, 如果是挂载的状态才继续, 否则提示
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//2. 读取输入的文件名/内容
String fileName = et_of_name.getText().toString();
String content = et_of_content.getText().toString();
//3. 得到指定文件的OutputStream
//1).得到sd卡下的files路径
String filesPath = getExternalFilesDir(null).getAbsolutePath();
//2).组成完整路径
String filePath = filesPath+"/"+fileName;
//3). 创建FileOutputStream
FileOutputStream fos = new FileOutputStream(filePath);
//4. 写数据
fos.write(content.getBytes("utf-8"));
fos.close();
//5. 提示
Toast.makeText(this, "保存完成", 0).show();
} else {
Toast.makeText(this, "sd卡没有挂载", 0).show();
}
}
public void read(View v) throws Exception {
// 1. 判断sd卡状态, 如果是挂载的状态才继续, 否则提示
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 2. 读取输入的文件名
String fileName = et_of_name.getText().toString();
// 3. 得到指定文件的InputStream
// 1).得到sd卡下的files路径
String filesPath = getExternalFilesDir(null).getAbsolutePath();
// 2).组成完整路径
String filePath = filesPath + "/" + fileName;
// 3). 创建FileInputStream
FileInputStream fis = new FileInputStream(filePath);
// 4. 读取数据, 成String
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len=fis.read(buffer))!=-1) {
baos.write(buffer, 0, len);
}
String content = baos.toString();
// 5. 显示
et_of_content.setText(content);
} else {
Toast.makeText(this, "sd卡没有挂载", 0).show();
}
}
// /storage/sdcard/atguigu/xxx.txt
public void save2(View v) throws IOException {
//1. 判断sd卡状态, 如果是挂载的状态才继续, 否则提示
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//2. 读取输入的文件名/内容
String fileName = et_of_name.getText().toString();
String content = et_of_content.getText().toString();
//3. 得到指定文件的OutputStream
//1). /storage/sdcard/
String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
//2). /storage/sdcard/atguigu/(创建文件夹)
File file = new File(sdPath+"/atguigu");
if(!file.exists()) {
file.mkdirs();//创建文件夹
}
//3). /storage/sdcard/atguigu/xxx.txt
String filePath = sdPath+"/atguigu/"+fileName;
//4). 创建输出流
FileOutputStream fos = new FileOutputStream(filePath);
//4. 写数据
fos.write(content.getBytes("utf-8"));
fos.close();
//5. 提示
Toast.makeText(this, "保存完成", 0).show();
} else {
Toast.makeText(this, "sd卡没有挂载", 0).show();
}
}
public void read2(View v) throws Exception {
// 1. 判断sd卡状态, 如果是挂载的状态才继续, 否则提示
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 2. 读取输入的文件名
String fileName = et_of_name.getText().toString();
// 3. 得到指定文件的InputStream
String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
String filePath = sdPath+"/atguigu/"+fileName;
FileInputStream fis = new FileInputStream(filePath);
// 4. 读取数据, 成String
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len=fis.read(buffer))!=-1) {
baos.write(buffer, 0, len);
}
String content = baos.toString();
fis.close();
// 5. 显示
et_of_content.setText(content);
} else {
Toast.makeText(this, "sd卡没有挂载", 0).show();
}
}
}
1.4 SQLite数据库存储
说明
Sqlite数据库
Sqlite数据库客户端
Sqlite数据库命令行
扫描二维码关注公众号,回复:
8794370 查看本文章
数据类型
Sqlite建表
Sqlite的CRUD语句
相关API
DBHelper.java
package com.atguigu.l04_datastorage;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* 数据库操作的帮助类
*
*/
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context,int version) {
super(context, "atguigu.db", null, version);
}
/**
* 什么时候才会创建数据库文件?
* 1). 数据库文件不存在
* 2). 连接数据库
*
* 什么时候调用?
* 当数据库文件创建时调用(1次)
* 在此方法中做什么?
* 建表
* 插入一些初始化数据
*/
@Override
public void onCreate(SQLiteDatabase db) {
Log.e("TAG", "DBHelper onCreate()");
//建表
String sql = "create table person(_id integer primary key autoincrement, name varchar,age int)";
db.execSQL(sql);
//插入一些初始化数据
db.execSQL("insert into person (name, age) values ('Tom1', 11)");
db.execSQL("insert into person (name, age) values ('Tom2', 12)");
db.execSQL("insert into person (name, age) values ('Tom3', 13)");
}
//当传入的版本号大于数据库的版本号时调用
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.e("TAG", "DBHelper onUpgrade()");
}
}
DBActivity.java
package com.atguigu.l04_datastorage;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
/**
* 测试Sqlite数据库存储
*
*
*/
public class DBActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db);
}
/*
* 创建库
*/
public void testCreateDB(View v) {
DBHelper dbHelper = new DBHelper(this, 1);
//获取连接
SQLiteDatabase database = dbHelper.getReadableDatabase();
Toast.makeText(this, "创建数据库", 0).show();
}
/*
* 更新库
*/
public void testUpdateDB(View v) {
DBHelper dbHelper = new DBHelper(this, 2);
//获取连接
SQLiteDatabase database = dbHelper.getReadableDatabase();
Toast.makeText(this, "更新数据库", 0).show();
}
/*
* 添加记录
*/
public void testInsert(View v) {
//1. 得到连接
DBHelper dbHelper = new DBHelper(this, 2);
SQLiteDatabase database = dbHelper.getReadableDatabase();
//2. 执行insert insert into person(name, age) values('Tom', 12)
ContentValues values = new ContentValues();
values.put("name", "Tom");
values.put("age", 12);
long id = database.insert("person", null, values);
//3. 关闭
database.close();
//4. 提示
Toast.makeText(this, "id="+id, 1).show();
}
/*
* 更新
*/
public void testUpdate(View v) {
DBHelper dbHelper = new DBHelper(this, 2);
SQLiteDatabase database = dbHelper.getReadableDatabase();
//执行update update person set name=Jack, age=13 where _id=4
ContentValues values = new ContentValues();
values.put("name", "jack");
values.put("age", 13);
int updateCount = database.update("person", values , "_id=?", new String[]{"4"});
database.close();
Toast.makeText(this, "updateCount="+updateCount, 1).show();
}
/*
* 删除
*/
public void testDelete(View v) {
// 1. 得到连接
DBHelper dbHelper = new DBHelper(this, 2);
SQLiteDatabase database = dbHelper.getReadableDatabase();
// 2. 执行delete delete from person where _id=2
int deleteCount = database.delete("person", "_id=2", null);
// 3. 关闭
database.close();
// 4. 提示
Toast.makeText(this, "deleteCount=" + deleteCount, 1).show();
}
/*
* 查询
*/
public void testQuery(View v) {
// 1. 得到连接
DBHelper dbHelper = new DBHelper(this, 2);
SQLiteDatabase database = dbHelper.getReadableDatabase();
// 2. 执行query select * from person
Cursor cursor = database.query("person", null, null, null, null, null, null);
//cursor = database.query("person", null, "_id=?", new String[]{"3"}, null, null, null);
//得到匹配的总记录数
int count = cursor.getCount();
//取出cursor中所有的数据
while(cursor.moveToNext()) {
//_id
int id = cursor.getInt(0);
//name
String name = cursor.getString(1);
//age
int age = cursor.getInt(cursor.getColumnIndex("age"));
Log.e("TAG", id+"-"+name+"-"+age);
}
// 3. 关闭
cursor.close();
database.close();
// 4. 提示
Toast.makeText(this, "count=" + count, 1).show();
}
/*
* 测试事务处理
* update person set age=16 where _id=1
* update person set age=17 where _id=3
*
* 一个功能中对数据库进行的多个操作: 要就是都成功要就都失败
* 事务处理的3步:
* 1. 开启事务(获取连接后)
* 2. 设置事务成功(在全部正常执行完后)
* 3. 结束事务(finally中)
*/
public void testTransaction(View v) {
SQLiteDatabase database = null;
try{
DBHelper dbHelper = new DBHelper(this, 2);
database = dbHelper.getReadableDatabase();
//1. 开启事务(获取连接后)
database.beginTransaction();
//执行update update person set age=16 where _id=1
ContentValues values = new ContentValues();
values.put("age", 16);
int updateCount = database.update("person", values , "_id=?", new String[]{"1"});
Log.e("TAG", "updateCount="+updateCount);
//出了异常
boolean flag = true;
if(flag) {
throw new RuntimeException("出异常啦!!!");
}
//执行update update person set age=17 where _id=3
values = new ContentValues();
values.put("age", 17);
int updateCount2 = database.update("person", values , "_id=?", new String[]{"3"});
Log.e("TAG", "updateCount2="+updateCount2);
//2. 设置事务成功(在全部正常执行完后)
database.setTransactionSuccessful();
} catch(Exception e) {
e.printStackTrace();
Toast.makeText(this, "出异常啦!!!", 1).show();
} finally {
//3. 结束事务(finally中)
if(database!=null) {
database.endTransaction();
database.close();
}
}
}
}