如何使SQLiteOpenHelper选择数据库而不是创建新数据库

时间:2016-09-08 15:15:56

标签: android sqlite android-sqlite

从SQLiteOpenHelper继承并从继承的类创建对象后,继承的类将创建一个全新的数据库来使用。如何让继承的类打开我之前创建的数据库,而不是创建一个新数据库?

3 个答案:

答案 0 :(得分:0)

调用SQLiteOpenHelper构造函数时,传入数据库文件名。如果使用相同的文件名,它将打开相同的数据库。虽然有多个班级打开相同的数据库,但实际上并不是我所建议的。

答案 1 :(得分:0)

If you are using a emulator then push the database file into the database folder of the project by opening android device manager->file Explorer->data->data->your project name then push the database file and then change the database name to your database name.




public class mydb extends SQLiteOpenHelper
{
    String DBPATH="/data/data/com.example.aman.java/databases/";
    static String DBNAME="java1db"; //here write your database name
    static int DBVERSION=3;
    Context mycontext;
    SQLiteDatabase mydb1;
    mydb(Context mycontext1)
    {
        super(mycontext1,DBNAME,null,DBVERSION);
        mycontext=mycontext1;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {

        }

    }

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




    }

    public void init()
    {
        mydb1=this.getReadableDatabase();
    }

    public void close1()
    {
        mydb1.close();
    }
}





if you are running on your device paste the database file in assets folder and paste this code in sqllitehelper class

void copyDatabase() throws IOException
    {

        InputStream myinput=mycontext.getAssets().open(DBNAME);
        String outfile=DBPATH + DBNAME;

        OutputStream myoutput=new FileOutputStream(outfile);
        int a;
        byte[] buffer=new byte[1024];
        while((a=myinput.read(buffer))>0)
        {
            myoutput.write(buffer,0,a);
        }
        myoutput.close();
        myinput.close();


    }

答案 2 :(得分:-1)

我相信这个问题已在此处提出:How to ship an Android application with a database?

我推荐使用SQLiteAssetHelper的“Alex Jolig”答案,如他们所关联的excellent tutorial所述。

相关问题