Android sdcard建立数据库

一. 如果手机是6.0以上的

1. 要初始化一下权限

private void initPermission() {

String permissions[] = {

Manifest.permission.INTERNET,

Manifest.permission.ACCESS_NETWORK_STATE,

Manifest.permission.MODIFY_AUDIO_SETTINGS,

Manifest.permission.WRITE_SETTINGS,

Manifest.permission.READ_PHONE_STATE,

Manifest.permission.ACCESS_WIFI_STATE,

Manifest.permission.CHANGE_WIFI_STATE,

Manifest.permission.SYSTEM_ALERT_WINDOW,

Manifest.permission.CAMERA,

Manifest.permission.MODIFY_AUDIO_SETTINGS,

Manifest.permission.RECORD_AUDIO,

Manifest.permission.WAKE_LOCK,

Manifest.permission.WRITE_EXTERNAL_STORAGE,

Manifest.permission.READ_EXTERNAL_STORAGE

    };

ArrayList toApplyList =new ArrayList();

for (String perm : permissions) {

if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {

toApplyList.add(perm);

//进入到这里代表没有权限.

        }

}

String tmpList[] =new String[toApplyList.size()];

if (!toApplyList.isEmpty()) {

ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList),123);

}

}

2. 回调下面的方法

@Override

public void onRequestPermissionsResult(int requestCode, String[] permissions,int[] grantResults) {

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

if (requestCode ==REQUEST_EXTERNAL_STORAGE) {

if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

MyLogcat.showTestLog(TAG,"授权成功");

}else {

MyLogcat.showTestLog(TAG,"授权失败,请去设置打开权限");

}

}

}


如果是继承SQLiteOpenHelper,按照下面的方式

SDCardDataBaseHelper.java

public class SDCardDataBaseHelper2extends SQLiteOpenHelper {

private static final StringTAG = SDCardDataBaseHelper2.class.getSimpleName();

private ContextmContext;

//db文件路径,保存在sd卡中

    public static final StringDB_PATH = Environment.getExternalStorageDirectory().getPath()

+ File.separator +"mydata" + File.separator;

//数据库名

    public static StringDB_NAME;

//数据库版本

    public static final int VERSION =1;

private static String getMyDatabaseName(String name) {

String databasename = name;

boolean isSdcardEnable =false;

String state = Environment.getExternalStorageState();

if (Environment.MEDIA_MOUNTED.equals(state)) {//SDCard是否插入

            isSdcardEnable =true;

}

MyLogcat.showTestLog(TAG,"isSdcardEnable = " + isSdcardEnable);

String dbPath =null;

if (isSdcardEnable) {

dbPath = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Finance/database/";

}else {//未插入SDCard,建在内存中

        }

File dbp =new File(dbPath);

if (!dbp.exists()) {

dbp.mkdirs();

}

MyLogcat.showTestLog(TAG,"dbPath = " + dbPath);

databasename = dbPath + databasename;

//        SQLiteDatabase database=SQLiteDatabase.openOrCreateDatabase(databasename,null);

        return databasename;

}

public SDCardDataBaseHelper2(Context context) {

super(context,getMyDatabaseName("test.db"),null,VERSION);//*; dbname;*;dbversion

        this.mContext = context;

}

@Override

    public void onCreate(SQLiteDatabase db) {

System.out.println("create");

//建表

        System.out.println("create over");

}

@Override

    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) {

System.out.println("update");

// db.execSQL("ALTER TABLE person ADD phone VARCHAR(12) NULL");

        System.out.println("update over");

}

下面的是在Activity中调用:

//数据库

SDCardDataBaseHelper2 mMysql;

SQLiteDatabase mDataBase;

//获取当前数据库

mMysql =new SDCardDataBaseHelper2(this);

mDataBase = mMysql.getReadableDatabase();


如果是继承OrmLiteSqliteOpenHelper,按照下面的方式

public class SDCardDataBaseHelperextends OrmLiteSqliteOpenHelper {

private static final StringTAG = SDCardDataBaseHelper.class.getSimpleName();

public static StringDB_NAME;

/**

    * helloDao 没张表对应一个

    */

    private DaohelloDao;

//db文件路径,保存在sd卡中

//    public static final String DB_PATH = Environment.getExternalStorageDirectory().getPath()

    public static final StringDB_PATH ="/sdcard"

            + File.separator +"db" + File.separator;

static{

//判断sd卡是否正常挂载

        if(! Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

DB_NAME ="status.db";//sd卡未正常挂载,则数据库还保存在默认位置

        }else{

DB_NAME =DB_PATH +"status.db";

File dbFolder =new File(DB_PATH);

// 目录不存在则自动创建目录

            if (!dbFolder.exists()){

dbFolder.mkdirs();

}

}

}

public SDCardDataBaseHelper(Context context) {

super(context,DB_NAME,null, Constants.DB_VERSION);

MyLogcat.showTestLog(TAG,"DB_NAME = " +DB_NAME);

}

@Override

    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {

MyLogcat.showTestLog(TAG,"onCreate start");

try {

TableUtils.createTable(connectionSource, Hello.class);

}catch (SQLException e) {

e.printStackTrace();

}

MyLogcat.showTestLog(TAG,"onCreate end");

}

@Override

    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource,int i,int i1) {

}

/**

    * 单例获取该Helper

    * 1.先把构造函数私有化

    * 2.对外提供一个静态方法

    * 3.在方法中判断如果已经存在就不再创建,如果不存在再创建这样就永远只有一个DataHelper对象

    * 4.为了线程安全,需要再方法钱提供一个线程安全关键字synchronized

*/

    private static SDCardDataBaseHelpersdCardDataBaseHelper;

public static synchronized SDCardDataBaseHelper getHeper(Context context) {

if (sdCardDataBaseHelper ==null) {

synchronized (SDCardDataBaseHelper.class){

if (sdCardDataBaseHelper ==null) {

sdCardDataBaseHelper =new SDCardDataBaseHelper(context);

}

}

}

return sdCardDataBaseHelper;

}

public Dao getHelloDao()throws SQLException {

if (helloDao ==null) {

helloDao = getDao(Hello.class);

}

MyLogcat.showTestLog(TAG,"getHelloDao()");

return helloDao;

}

public synchronized void clearData(Class clase) {

try {

TableUtils.clearTable(connectionSource, clase);

}catch (SQLException e) {

e.printStackTrace();

}

}

@Override

    public synchronized SQLiteDatabase getWritableDatabase() {

return SQLiteDatabase.openDatabase(DB_NAME,null,

SQLiteDatabase.OPEN_READWRITE);

}

public synchronized SQLiteDatabase getReadableDatabase() {

return SQLiteDatabase.openDatabase(DB_NAME,null,

SQLiteDatabase.OPEN_READONLY);

}

}

在Activity中调用

SDCardDataBaseHelper.getHeper(this);

MyLogcat.showTestLog(TAG,"new File(\"/sdcard/db\").listFiles().length = " +new File("/sdcard/db").listFiles().length);

if (new File("/sdcard/db").listFiles().length <=0) {

SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(

SDCardDataBaseHelper.DB_NAME,null);

SDCardDataBaseHelper orm =new SDCardDataBaseHelper(this);

orm.onCreate(db);

db.close();

}

HelloDao helloDao =new HelloDao(this);

helloDao.add(new Hello("sdcard","male",23));

你可能感兴趣的:(Android sdcard建立数据库)