如何在Android中使用数据库文件夹中的SQLITE Database文件夹?

时间:2014-06-04 07:29:52

标签: android database android-sqlite assets

我正在尝试在Android中编写代码以使用数据库文件夹中现有的sqlite数据库文件。我将数据库从Asset文件夹复制到数据库文件夹。现在我想使用我的Provider中的sqlite文件,但我没有找到任何技术来实现它。

我的代码:

MainActivity.java

package com.example.testtable;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;


public class MainActivity extends Activity
{

@Override
protected void onCreate(Bundle savedInstanceState) 
{

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    ContentValues updateStatus = new ContentValues();

    updateStatus.put(TestProvider.Name,"Android Code");

    this.getApplicationContext().getContentResolver().update(TestProvider.CONTENT_URI, updateStatus, "Id=? AND AgeId=? AND PhoneNo=?", new String[]{"1","25","9807456783"});


}   }   

TestProvider.java

package com.example.testtable;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.util.Log;


public class TestProvider extends ContentProvider
{


private SQLiteDatabase database;

 static final String PROVIDER_NAME = "com.example.testtable.provider.TestProvider";

static final String TestTable = "MyDetails";

static final String URL = "content://" + PROVIDER_NAME +"/" +TestTable;

static final Uri CONTENT_URI = Uri.parse(URL);

static final String TestId = "TestId";

static final String Name = "Name";

static final String ID = "Id";

static final String AgeId = "AgeId";

static final String PhoneNo = "PhoneNo";

static final int DATABASE_VERSION = 1;


@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public String getType(Uri uri) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
    // TODO Auto-generated method stub
    return null;
}

private static class DatabaseHelper extends SQLiteOpenHelper
{
    private Context cont;

    private SQLiteDatabase database;

    public static String DB_PATH;



    public static final String DB_NAME = "testdb.sqlite";

        DatabaseHelper(Context context)
        {

            super(context,null,null,DATABASE_VERSION);

            this.cont = context;

             String packageName = context.getPackageName();
                DB_PATH = "/data/data/" + packageName + "/databases/";


        }

           @Override
           public void onCreate(SQLiteDatabase db)
           {

                try
                {

                    InputStream myInput = cont.getAssets().open(DB_NAME);

                    String outFileName = "/data/data/testtable/databases/" + DB_NAME;

                    OutputStream myOutput = new FileOutputStream(outFileName);

                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = myInput.read(buffer)) > 0) {
                        myOutput.write(buffer, 0, length);
                    }

                    myOutput.flush();
                    myOutput.close();
                    myInput.close();

                }
                catch(IOException e)
                {

                }

           }

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

               //

           }



}


@Override
public boolean onCreate() 
{

    Context context = getContext();

    DatabaseHelper dbHelper = new DatabaseHelper(context);

    database = dbHelper.getWritableDatabase();

    return (database==null)? false:true;

}

@Override
public Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder) 
{

    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    qb.setTables(TestTable);

    Cursor c = qb.query(database,   projection, selection, selectionArgs, 
            null, null, sortOrder);

    c.setNotificationUri(getContext().getContentResolver(), uri);

    return c;

}

@Override
public int update(Uri uri, ContentValues values, String selection,String[] selectionArgs) 
{

    int count = 0;

    switch(uriMatcher.match(uri))
    {

        case 1:

                count = database.update(TestTable, values, selection, selectionArgs);

        break;  

        case 2:
            count = database.update(TestTable, values, selection, selectionArgs);

                break;  

        default:

            throw new IllegalArgumentException("Unknown URL: "+uri);
    }


     getContext().getContentResolver().notifyChange(uri, null);

     return count;
}

 }

这些都是我上面的代码。请告诉我如何将数据库文件夹中复制的数据库文件用于我的SQL查询。

请建议我解决一下。

3 个答案:

答案 0 :(得分:0)

AFAIK,DatabaseHelper中的super()调用必须带有文件名(并且你有空)。在尝试操作之前不会创建任何文件,您是否尝试过提供文件名?作为后备,您是否考虑过使用外部文件系统?

答案 1 :(得分:0)

我发现您的代码有两个问题:

  • (1)您的databasehelper必须知道要使用的数据库的名称
  • (2)你的代码假设数据库文件位于/data/data/testtable/databases/这可能会为不同的android-version / sdcard,.....

// TestProvider.java

public class TestProvider extends ContentProvider {

    public static final String DB_NAME = "testdb.sqlite";

    // (2) let android give you the path to the local database
    public File getLocalDatabaseFile(Context context) {
        return context.getDatabasePath(DB_NAME);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context)
        {
            // (1) parameter#2: databasehelper must know the name of the database to use
            super(context,DB_NAME,null,DATABASE_VERSION);

             ...
        }
    }

       @Override
       public void onCreate(SQLiteDatabase db)
       {
            try
            {
                InputStream myInput = cont.getAssets().open(DB_NAME);

                // (2) let android give you the path to the local database
                OutputStream myOutput = new FileOutputStream(
                          getLocalDatabaseFile(this.context));

答案 2 :(得分:0)

您可以使用android-sqlite-asset-helper将数据库从assets文件夹复制到手机。

扩展SQLiteAssetHelper而不是SQLiteOpenHelper

public class MyDatabase extends SQLiteAssetHelper {

    private static final String DATABASE_NAME = "northwind.db";
    private static final int DATABASE_VERSION = 1;

    public MyDatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
}

并在内容提供商中使用MyDatabase的实例。 第一次调用getReadableDatabasegetWritableDatabase时,数据库将被复制到手机中。