1.基础:
1.1.Android 数据存储路径:
内部存储:
/data/data/packageName/databases: 数据库
/data/data/packageName/file: 内部存储
/data/data/packageName/shared_prefs : sp键值对存储
sdcard下:
/storage/sdcard/Android/data/packageName : 应用卸载时删除,sd对应应用包的内部存储
/storage/sdcard/xxx : 应用卸载时不删除,6.0需要权限
模拟器类型必须是Google APIc才有root权限可以查看data/data目录
2. shared_prefs Api 键值对使用
// /data/data/packageName/shared_prefs
private SharedPreferences sp;
public void spOperator(View view){
//1. 得到sp对象
sp = getSharedPreferences("atguigu", Context.MODE_PRIVATE);
//2. 得到editor对象
SharedPreferences.Editor edit = sp.edit();
// 3. sp 存储数据
edit.putString("username", "xiaoming").commit();
// 4. sp 读取数据
String str=sp.getString("username","");
Log.e("denganzhi1",str);
}
3. 安卓内部存储file
// /data/data/packageName/file 安卓内部存储默认
public void writeImgage(View view) throws IOException {
AssetManager manager = getAssets();
// 会自动去assert目录下找
InputStream is = manager.open("a.txt");
// 会自动打开 /data/data/packageName/file 目录
FileOutputStream fos = openFileOutput("a.txt", 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();
}
public void readImgage(View view) throws IOException {
// 获取路径
// /data/data/packageName/file 目录
String filesPath = getFilesDir().getAbsolutePath()+"/a.txt";
BufferedReader reader=new BufferedReader(new FileReader(filesPath));
String line=null;
while(null!=(line=reader.readLine())){
Log.e("line:",line);
}
reader.close();
}
4. sd对应应用包的内部存储
// /storage/emulated/0/Android/data/com.example.myapplication/files : 应用卸载时删除
public void writeSD(View view) throws IOException {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String filesPath = getExternalFilesDir(null).getAbsolutePath();
Log.e("path:",filesPath);
// : /storage/emulated/0/Android/data/com.example.myapplication/files
String filePath = filesPath+"/"+"a.txt";
FileOutputStream fos = new FileOutputStream(filePath);
fos.write("写sdcard".getBytes("utf-8"));
fos.close();
}
}
public void readSD(View view) throws IOException {
// 1. 判断sd卡状态, 如果是挂载的状态才继续, 否则提示
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
String filesPath = getExternalFilesDir(null).getAbsolutePath()+"/a.txt";
FileInputStream fis = new FileInputStream(filesPath);
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();
Log.e("readSD-->content:",content);
baos.close();
fis.close();
}
}
5. sd外部存储
<!-- 操作sd卡 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
// 权限回调
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
try {
writeSdOut();
} catch (IOException e) {
e.printStackTrace();
}
} else
{
// Permission Denied
Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
return;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
// 写入SD卡内容
public static int MY_PERMISSIONS_REQUEST_CALL_PHONE=100;
public void writeSDW(View view) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},MY_PERMISSIONS_REQUEST_CALL_PHONE);
} else
{
try {
writeSdOut();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void writeSdOut() throws IOException {
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// /storage/emulated/0
String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
Log.e("sdPath:",sdPath);
// /storage/emulated/0
File file = new File(sdPath+"/atguigu");
if(!file.exists()) {
file.mkdirs();//创建文件夹
}
String filePath = sdPath+"/atguigu/"+"a.txt";
FileOutputStream fos = new FileOutputStream(filePath);
//4. 写数据
fos.write("sd卡外部存储".getBytes("utf-8"));
fos.close();
}
}
// 读取SD卡内容
public void readSDW(View view) throws IOException {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
// /storage/emulated/0
File file = new File(sdPath+"/atguigu");
String filePath = sdPath+"/atguigu/"+"a.txt";
Log.e("sdPath:",sdPath);
FileInputStream fis = new FileInputStream(filePath);
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();
Log.e("readSDW-->content:",content);
fis.close();
}
}
6. sqlite数据库存储
路径: /data/data/packageName/datebases
联系人App的数据库路径: data/data/com.android.prividers.contacts
打开导出本地.sqlite数据工具: SQLite Expert
6.1. 数据库基本操作:
工具:Sqlite Expert Personal3 查看 .sqlite数据库,常用sql语句
## 建表
create table employee(
_id integer primary key autoincrement,
name varchar,
salary double,
birthday date
)## 插入数据
insert into employee(name,salary,birthday) values("Tom",100000,"1994-12-12");## 删除数据
delete from employee where _id=1## 更新数据
update employee set name="xiaozhang" where _id=2;## 查找
select * from employee where _id=2;
使用adb命令查看:
adb shell
cd /data/data
cd com.android.providers.contacts
cd databases
sqlite3 contacts2.db
.tables :查看所有表
select * from data;
6.2. Android Api对sqlite数据库操作
基础类:
package com.example.myapplication;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* 数据库操作的帮助类
* @author denganzhi
*
*/
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()-->"+"oldVersion:"+oldVersion + "newVersion:"+newVersion);
}
// 还有版本下降的时候调用的方法onDowngrade
}
6.2.1. 创建数据库:
/***
* long insert()
* long update
* int delete
* Cursor query: 执行select的sql 返回Cursor,关标,Cursor就是一行记录
* int getCount(): 匹配记录总数
* boolean moveToNext() 关标移动到下一条记录前面
* Xxx getXxx(columnIndex) 根据字段下标得到值
*
*
* A表格:
* 含义 id name
* 记录1 1 ming
* -> 记录2 2 zhong
*
* moveToNext: 移动指向记录的关标
*
* select id ,name from empolyee _id=3
* cursor.getInt(0) id的值
* cursor.getString(1) name的值
*
*
*
* void execuSql(sql) :执行sql
* @param view
*/
public void creatTable(View view){
DBHelper dbHelper=new DBHelper(this,1);
// 创建数据源库
// dbHelper.getWritableDatabase(); //本地空间满了如果,继续插入没有反应
// 连接数据库,得到连接
SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase(); // 本地空间满了如果,继续插入抛异常
}
6.2.2. 更新数据库版本
public void updateTable(View view){
DBHelper dbHelper=new DBHelper(this,2);
// 连接数据库才会更新
// 回调 onUpgrade 回调方法,比如更新一些字段
SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
}
6.2.3. 数据的插入、修改、删除、查询
public void insertFun(View view){
DBHelper dbHelper=new DBHelper(this,2);
SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
//insert into person (name, age) values ('Tom1', 11)
ContentValues contentValues=new ContentValues();
contentValues.put("name","denganzhi");
contentValues.put("age",25);
long id= sqLiteDatabase.insert("person",null,contentValues);
sqLiteDatabase.close();
Toast.makeText(MainActivity.this,"longid:"+id,Toast.LENGTH_SHORT).show();
}
public void updateFun(View view){
DBHelper dbHelper=new DBHelper(this,2);
SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("age","300000");
int updateCount=sqLiteDatabase.update("person",contentValues,"_id=?",new String[]{"5"});
sqLiteDatabase.close();
Toast.makeText(MainActivity.this,"updateCount:"+updateCount,Toast.LENGTH_SHORT).show();
}
public void deleteFun(View view){
DBHelper dbHelper=new DBHelper(this,2);
SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
int deleteId= sqLiteDatabase.delete("person","_id=5",null);
sqLiteDatabase.close();
Toast.makeText(MainActivity.this,"deleteId:"+deleteId,Toast.LENGTH_SHORT).show();
}
public void selectFun(View view){
DBHelper dbHelper=new DBHelper(this,2);
SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
// select * from person
//query(String table, String[] columns, String selection,
// String[] selectionArgs, String groupBy, String having,
// String orderBy)
Cursor cursor = sqLiteDatabase.query("person",null,"_id=?",new String[]{"3"},null,null,null);
int count =cursor.getCount(); // 得到上面匹配的总数
while(cursor.moveToNext()){
int id= cursor.getInt(0);
String name =cursor.getString(1);
int age= cursor.getInt(cursor.getColumnIndex("age")); //如果记得名字了可以这样
Log.e("denganzhi","count:"+count + " id:"+id +" name:"+ name + " age:"+ age);
}
cursor.close();
sqLiteDatabase.close();
}
6.2.4. 数据库事务操作
/***
* 事务: 多个操作,要么都成功,要么都失败回滚
* @param view
*/
public void operatorTransiction(View view){
DBHelper dbHelper=new DBHelper(this,2);
SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
// 1.开启事务, 不会自动保存提交了
sqLiteDatabase.beginTransaction();
ContentValues contentValues1=new ContentValues();
contentValues1.put("age","300000");
int updateCount1=sqLiteDatabase.update("person",contentValues1,"_id=?",new String[]{"1"});
int j=1/0;
contentValues1=new ContentValues();
contentValues1.put("age","200000");
updateCount1=sqLiteDatabase.update("person",contentValues1,"_id=?",new String[]{"2"});
//2. 设置事务在全局
sqLiteDatabase.setTransactionSuccessful();
// 3. 结束事务
sqLiteDatabase.endTransaction();
sqLiteDatabase.close();
}