首先,需要声明权限,如果是6.0以上,需要运行时权限
AndroidManifest.xml中:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
如果系统时6.0以上,就需要申请运行时权限:
if(Build.VERSION.SDK_INT >= 23){
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}else {
initSQLFile(); // 调用创建文件路径的方法
}
}
1,创建需要指定的路径(文件夹)
public static final String PATH_ONE = "KogBill";
public static final String PATH_NAME = "KogBill.db";
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
String path1 = path + File.separator + PATH_ONE; //需要创建的路径
String path2 = path + File.separator + PATH_ONE +
File.separator + PATH_NAME; //需要创建的文件
//创建路径
File f1 = new File(path1);
if(!f1.exists()){
f1.mkdirs();
//目录创建成功, ...../0/KogBill/
}
2,创建数据库文件(.db文件)及表
//定义一个内部类(或者新建类),继承 SQLiteOpenHelper
class MySQLiteHelper extends SQLiteOpenHelper{
private static final int DATEBASE_VERSION = 1; //定义版本号
private static final String CREATE_TABLE = "create table kog_bill (" //创建表语句
+ "_id integer primary key autoincrement,"
+ "date text, "
+ "breakfast text, "
+ "lunch text,"
+ "dinner text,"
+ "happy text,"
+ "other text,"
+ "spare text)";
//自定义构造方法,简化自动生成的构造方法,path 是主要指定病创建db文件的路径
// .../.../KogBill/kog_bill.db
public MySQLiteHelper(Context context , String path){
this(context,path,null,DATEBASE_VERSION);
}
//实现接口必须实现的构造方法
public MySQLiteHelper(Context context, String name, CursorFactory factory, int version){
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// 第一次创建数据库时 才会调用
Log.e("mylog", "创建数据库表");
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
//在主方法中,创建这个类对象,并获取db对象
MySQLiteHelper mSQL = new MySQLiteHelper(MainActivity.this,path2 );
db = mSQL.getWritableDatabase();
3,通过db 对象实现增删改查
…此处省略