/**
* SharedPreferences 存储
*
* @param context
*/
public void myShareedPerferences(Context context) {
/*
* getSharedPreferences(String name, int mode)
* name 自定义即可
* mode 设置SharedPreferences操作的权限(一般选择Context.MODE_PRIVATE(只能被本程序使用))
* Editor 编辑器(可以理解为笔)
* 以键值对的形式存储,只能存储简单的数据类型
*/
SharedPreferences sp = context.getSharedPreferences("configs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
//保存
editor.putString("String", "String");
editor.putBoolean("boolean", false);
editor.putFloat("float", (float) 1.0);
editor.putInt("int", 1);
editor.putLong("long", (long) 1.0);
Set set = new HashSet();
editor.putStringSet("set", set);
editor.commit(); //保存完了之后得提交
//读取
String str = sp.getString("String", ""); //根据键获取值,第二个参数是设置没有数据时的默认值
}
保存在app内部存储空间,非公开的
/**
* 内部存储:openFileOutput()、openFileInput()、deleteFile()
* 保存位置:/data/data/app所在的包名/files/...
* 特点:内部存储里的东西会随着app的卸载而清除
* 程序到磁盘(输出流)
* 磁盘到程序(输入流)
*/
public void save(Context context) {
if (TextUtils.isEmpty("File")) return;
try {
/*
* 保存
* 第一个参数需要存储的文件名称
* 第二个参数操作权限
* 打开一个用来读写的文件,该文件是与当前上下文所在的包有关,而且调用该方法不需要添加权限
* 因为这是内部存储
*/
FileOutputStream fos = context.openFileOutput("File", Context.MODE_PRIVATE);
fos.write(new String("string").getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
/*
* 打开文件
* 获取只读的输入流
*/
FileInputStream fis = context.openFileInput("File");
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
/*
* 删除文件
*/
boolean deleteFile = context.deleteFile("File");
if (deleteFile) {
System.out.println("删除成功");
}
}
存储在app外部,可以供别的程序使用的数据,app卸载之后数据一般不会被清除
内部和外部可以说是一体的
公共空间
/**
* ExternalStorage
* 存储的工具类(本文以存读图片为例)
* Android4.4之后(对应API19)需要添加权限
*/
public class ExternalStorageUtil {
//getExternalStorageDirectory()外部存储的根路径
//存储路径
public static final String STORE_PATH = Environment
.getExternalStorageDirectory()
+ "/Snow/" + "Sky";
//获取外部存储的状态,判断SD卡是否已挂载
public static boolean isMounted() {
String state = Environment.getExternalStorageState();
return state.equals(Environment.MEDIA_MOUNTED);
}
//保存图片
public static boolean saveImage(String fileName, byte[] data) {
if (!isMounted()) {
return false;
}
File dir = new File(STORE_PATH);
if (!dir.exists()) { //如果文件不存在
dir.mkdirs(); //创建文件
}
try {
FileOutputStream fos = new FileOutputStream(new File(dir, fileName));
fos.write(data);
fos.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
//读取图片
public static Bitmap readImg(String fileName) {
if (!isMounted()) {
return null;
}
File imgFile = new File(STORE_PATH, fileName);
if (imgFile.exists()) {//如果文件存在才进行读取
return BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}
return null;
}
}
工具类写好了,接下来就是调用了,保存图片:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.test);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//将图片进行压缩---》会见图片的信息保存到baos中
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
bitmap.recycle(); //回收图片
boolean isSave = ExternalStorageUtil.saveImage("test.jpg", baos.toByteArray());
if (isSave) {
Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
}
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
接下来是读取:
Bitmap bitmap = ExternalStorageUtil.readImg("test.jpg");
/外部存储所需要的权限
ActivityCompat.requestPermissions(this, new String[]{android
.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1001);
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1001:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//创建文件夹
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File file = new File(Environment.getExternalStorageDirectory() + "/Snow/Sky/");
if (!file.exists()) {
Log.d("ljm", "path1 create:" + file.mkdirs());
}
}
break;
}
}
}
Manifest.xml中的权限我就不贴出来了
Android中,使用SQLite来进行数据库存储,需要写一个类来继承SQLiteOpenHelper
public class MySQLite extends SQLiteOpenHelper {
private static String DB_NAME = "persons.db"; //此处一定要添加数据库的后缀 .db
private static int DB_VERSION = 1; //版本号必须 >=1
/*
* @param context
* @param name 数据库名称
* @param factory 游标工厂
* @param version 版本
* 本类只需要上下文参数,其他参数在本类定义
* 构造方法指定了数据库的名称和版本信息
*/
public MySQLite(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public MySQLite(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
super(context, name, factory, version, errorHandler);
}
/**
* 在这个方法中建表
*
* @param db 如果想要建多个表,多次执行 db.execSQL(sql);
*/
@Override
public void onCreate(SQLiteDatabase db) {
//SQLite数据库中字段一般是不区分类型的,但是主键必须是整型的
String sql = "CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
"name CHAR(10)," +
"age INTEGER(10)," +
"sex CHAR(10))"; //建表语句
db.execSQL(sql);
}
/**
* 用来升级数据库的方法
*
* @param db
* @param oldVersion 旧版本
* @param newVersion 新版本
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) { //根据需求做操作
String sql = "DROP TABLE IF EXITS person";
db.execSQL(sql);
onCreate(db);
}
}
类写好了,接下来就是使用了:
MySQLite sqLite = new MySQLite(context);
// 需要调用一下两个方法之一,数据库才能正真创建出来
// 正常情况下,两个方法得到的结果是一样的
// 非正常情况下,比如明确要求以只读的方式来打开数据库或者磁盘满了,getReadableDatabase()得到的是只读的数据库
// SQLiteDatabase readableDatabase = sqLite.getReadableDatabase();
SQLiteDatabase writableDatabase = sqLite.getWritableDatabase();
/**
* 添加数据
* @param db
*/
public void insert(SQLiteDatabase db){
//使用sql语句添加数据,这个语句的缺陷是不知道数据是否添加成功
/*String sql = "insert into person (name,age) values('name',1)";
db.execSQL(sql);*/
//表名,null,values
ContentValues values = new ContentValues();
values.put("name","name");
values.put("age",1);
values.put("sex","男");
//返回值:最近插入的那一行的行号
Long result = db.insert("person",null,values);
if (result > 0){
Log.i("添加数据","添加成功");
}
}
查:
/**
* 查询数据
* 注:增删改都可以使用sql语句执行
* 因为查需要返回数据,所以不能使用sql语句进行查询
* @param db
*/
public void query(SQLiteDatabase db){
//sql语句:select * from person where name = "name"
//db.rawQuery(sql,selectionArgs)
//参数较多:表名、列(查所有数据时填null)、条件语句 where、条件字段,参数值、分组列、分组条件、排序
//Cursor:游标 --> 结果集
Cursor cursor = db.query("person",null,"name=?",new String[]{"name"},null,null,null);
//遍历结果集,可以将数据库中所有的数据都读取到
while (cursor.moveToNext()){
int index = cursor.getColumnIndex("name"); //根据列名获取编号
String nameValue = cursor.getString(index);
int ageValue = cursor.getInt(cursor.getColumnIndex("age"));
}
//下面是根据条件查询某一列的数量
String sql = "select count(notificationId) from person where customer = 'name' and age = 0";
Cursor cursor1 = db.rawQuery(sql, null);
cursor.moveToFirst();
Long count = cursor.getLong(0);
if (count > 0) {
Log.i("000", "查看还有多少条没有查看" + count);
} else {
Log.i("000", "查看还有多少条没有查看" + count);
}
}
/**
* 修改数据
* @param db
*/
public void updata(SQLiteDatabase db){
ContentValues values = new ContentValues();
values.put("name","updata");
int result = db.update("person", values, "age=?", new String[]{String.valueOf(0)});
if (result > 0) {
System.out.println("修改成功");
}
}
/**
* 删除数据
* @param db
*/
public void deleted(SQLiteDatabase db){
int result = db.delete("person", "name=?", new String[]{"updata"});
if (result > 0) {
System.out.println("删除成功");
}
}
因第一次发博客,页面不怎么会整理,敬请见谅!