在android中创建数据库文件 [英] Create database file in android

查看:539
本文介绍了在android中创建数据库文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,在应用程序数据中创建了应用程序的默认数据库文件.是否可以在我们自己的路径(例如"/mnt/sdcard/test.db")中创建数据库文件?

By default database file of an application is created in the application data. Is it possible to create database file in our own path like "/mnt/sdcard/test.db" ?

我正在通过扩展SQLiteOpenhelper创建数据库文件,但是它是在应用程序数据位置中创建的.我想在sdcard位置创建.我尝试使用"db.OpenorCreateDatabase(Path)". 当我尝试读取该文件时,它在该位置创建了一个db文件,该文件崩溃了.该怎么办?

I am creating database file by extending SQLiteOpenhelper, but its creating in app data location. I want to create in sdcard location. I tried with "db.OpenorCreateDatabase(Path)". Its creating a db file in that location, when i tried to read that file its crashing.How to do it?

推荐答案

如果提供自定义ContextClass且在目标目录中具有写访问权限,则可以将SQLiteOpenHelper与自定义路径一起使用(至少在android 2.2中使用).

You can use the SQLiteOpenHelper with a custom path (at least with android 2.2) if you provide a custom ContextClass and if you have write access in the target directory.

public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;
    .....

DatabaseHelper(final Context context, String databaseName) 
    {
       super(new DatabaseContext(context), databaseName, null, DATABASE_VERSION);
    }
}

这是自定义DatabaseContext类,可完成所有操作

And here is the custom DatabaseContext class that does all the magic

class DatabaseContext extends ContextWrapper {

private static final String DEBUG_CONTEXT = "DatabaseContext";

public DatabaseContext(Context base) {
    super(base);
}

@Override
public File getDatabasePath(String name) 
{
    File sdcard = Environment.getExternalStorageDirectory();    
    String dbfile = sdcard.getAbsolutePath() + File.separator+ "databases" + File.separator + name;
    if (!dbfile.endsWith(".db"))
    {
        dbfile += ".db" ;
    }

    File result = new File(dbfile);

    if (!result.getParentFile().exists())
    {
        result.getParentFile().mkdirs();
    }

    if (Log.isLoggable(DEBUG_CONTEXT, Log.WARN))
    {
        Log.w(DEBUG_CONTEXT,
                "getDatabasePath(" + name + ") = " + result.getAbsolutePath());
    }

    return result;
}

@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) 
{
    SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
    // SQLiteDatabase result = super.openOrCreateDatabase(name, mode, factory);
    if (Log.isLoggable(DEBUG_CONTEXT, Log.WARN))
    {
        Log.w(DEBUG_CONTEXT,
                "openOrCreateDatabase(" + name + ",,) = " + result.getPath());
    }
    return result;
}
}

这篇关于在android中创建数据库文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆