簡體   English   中英

如何將外部大型Sqlite導入新的android項目

[英]How can I import external large Sqlite to my new android project

我有要在我的android項目中使用的db xxx.sqlite(8Mo),所以我使用此代碼,但它不起作用Datahelper.java

public class Datahelper extends SQLiteOpenHelper {

private String dbName;
private String db_path;
private Context context;


public Datahelper(Context context, String dbName) {
    super(context, dbName, null, 1);
    this.dbName = dbName;
    this.context = context;
    db_path = "/data/data" + context.getPackageName() + "/databases/";

}

/**
 * Check if the database already exist to avoid re-copying the file each
 * time you open the application.
 *
 * @return true if it exists, false if it doesn't
 */
public boolean checkExist() {

    SQLiteDatabase checkDB = null;

    try {
        String myPath = db_path + dbName;
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {
        e.printStackTrace();
        // database does't exist yet.

    } catch (Exception ep) {
        ep.printStackTrace();
    }

    if (checkDB != null) {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * Creates a empty database on the system and rewrites it with your own
 * database.
 * */
public int importIfNotExist() throws IOException {
      int a=0;
    boolean dbExist = checkExist();

    if (dbExist) {
        a=0;
        // do nothing - database already exist
    } else {

        // By calling this method and empty database will be created into
        // the default system path
        // of your application so we are gonna be able to overwrite that
        // database with our database.
        this.getReadableDatabase();

        try {

            copyDatabase();
          a=2;
        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }
    return a;

}

private void copyDatabase() throws IOException {
    InputStream is = context.getAssets().open(dbName);

    OutputStream os = new FileOutputStream(db_path + dbName);

    byte[] buffer = new byte[4096];
    int length;
    while ((length = is.read(buffer)) > 0) {
        os.write(buffer, 0, length);
    }
    os.flush();
    os.close();
    is.close();
    this.close();
}

@Override
public void onCreate(SQLiteDatabase db) {


}

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


} }

在我的activity.java中

Datahelper dbHelper = new Datahelper(
            getBaseContext(), "xxx.sqlite");
    try {
        dbHelper.importIfNotExist();
    } catch (IOException e) {
        e.printStackTrace();
    }

我的一些朋友告訴我,我的數據庫是8Mo,非常大,我嘗試將其放在res / raw中,但它不起作用,並且將其放在資產文件夾中,並且不起作用。 請有人幫忙。

編輯

檢查本教程


您可以使用此功能從舊數據庫中獲取所有數據,並用您自己的數據庫替換“ COLUMN_NAME”。

public boolean consulta(String titulo, String issn){
        String a="",b="",c="";
        boolean respuesta = false;
        cursor = db.rawQuery("select * from "+ TABLA_NAME, null);
        if (cursor.getCount() != 0) {
            if (cursor.moveToFirst()) {
                do {
                    a = cursor.getString(cursor.getColumnIndex("COLUMN_NAME1")); 
                    b = cursor.getString(cursor.getColumnIndex("COLUMN_NAME2"));
                    c = cursor.getString(cursor.getColumnIndex("COLUMN_NAME3"));
                }while (cursor.moveToNext()); 
            }
        }
        respuesta = a+"-"+b+"-"+c;
        cursor.close(); // cierra cursor
        return respuesta;
    }

使用此將數據保存為txt

private void saveData(String data){
        try {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/dataFile.txt");
            file.createNewFile();
            FileOutputStream fOut = new FileOutputStream(file);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
            myOutWriter.append(data);
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(), "LISTO, se escribio en la tarjeta SD", Toast.LENGTH_SHORT).show();//mensaje de que se escribio
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();// mensaje de error
        }
    }

之后,在新的Android項目中,使用此功能從txt文件獲取數據並將其存儲在新數據庫中。

private void readTxt(File file){
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/dataFile.txt");
        StringBuilder text = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) { 
                text.append(line);
                text.append('\n');
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String data = "";
        StringTokenizer st = new StringTokenizer(text,"-");
        while(st.hasMoreTokens()){
            // you can set values to the column as much as you have
            ContentValues contentValues = new ContentValues();
            contentValues.put("COLUMN_NAME1", st.nextToken());
            contentValues.put("COLUMN_NAME2", st.nextToken());
            contentValues.put("COLUMN_NAME3", st.nextToken());
            database.insert(TABLA_PRINCIPAL, null, contentValues); // se inserta en la BD
            Toast.makeText(getBaseContext(), "Datos agregados", Toast.LENGTH_LONG).show(); // muestra mensaje de inserccion satisfactorio
        }
    }

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM