首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Android应用程序中使用现有数据库

如何在Android应用程序中使用现有数据库
EN

Stack Overflow用户
提问于 2012-02-02 16:54:28
回答 2查看 220.1K关注 0票数 331

我已经创建了一个SQLite数据库。我想在我的Android项目中使用这个数据库文件。我想将这个数据库与我的应用程序捆绑在一起。

应用程序如何访问此数据库并将其用作其数据库,而不是创建一个新数据库?

EN

回答 2

Stack Overflow用户

发布于 2012-12-13 01:15:32

关于这个问题,我在其他DatabaseHelpers上遇到了麻烦,不知道为什么。

这是对我有效的方法:

代码语言:javascript
复制
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

  private static final String TAG = DatabaseHelper.class.getSimpleName();

  private final Context context;
  private final String assetPath;
  private final String dbPath;

  public DatabaseHelper(Context context, String dbName, String assetPath)
      throws IOException {
    super(context, dbName, null, 1);
    this.context = context;
    this.assetPath = assetPath;
    this.dbPath = "/data/data/"
        + context.getApplicationContext().getPackageName() + "/databases/"
        + dbName;
    checkExists();
  }

  /**
   * Checks if the database asset needs to be copied and if so copies it to the
   * default location.
   * 
   * @throws IOException
   */
  private void checkExists() throws IOException {
    Log.i(TAG, "checkExists()");

    File dbFile = new File(dbPath);

    if (!dbFile.exists()) {

      Log.i(TAG, "creating database..");

      dbFile.getParentFile().mkdirs();
      copyStream(context.getAssets().open(assetPath), new FileOutputStream(
          dbFile));

      Log.i(TAG, assetPath + " has been copied to " + dbFile.getAbsolutePath());
    }

  }

  private void copyStream(InputStream is, OutputStream os) throws IOException {
    byte buf[] = new byte[1024];
    int c = 0;
    while (true) {
      c = is.read(buf);
      if (c == -1)
        break;
      os.write(buf, 0, c);
    }
    is.close();
    os.close();
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }
}
票数 11
EN

Stack Overflow用户

发布于 2012-02-02 17:03:19

您可以通过使用content provider来完成此操作。应用程序中使用的每个数据项对应用程序来说都是私有的。如果应用程序想要跨应用程序共享数据,则只有一种技术可以实现这一点,即使用提供访问私有数据接口的内容提供商。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9109438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档