2010-12-13 10 views
5

Non capisco perché non riesca a copiare il mio file db (abic_) nella directory dell'applicazione ("/ data/data /" + context.getPackageName() + "/ database")Copia il mio DB SQLite dalla cartella Asset a

questa è la mia classe DataBaseHelper:


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

import android.content.Context; 
import android.database.SQLException; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteException; 
import android.database.sqlite.SQLiteOpenHelper; 


public class DataBaseHelper extends SQLiteOpenHelper{ 

    //The Android's default system path of your application database. 
    private String DB_PATH; 

    private static String DB_NAME = "abic_"; 
    private static final Integer DB_VERSION = 1; 

    private SQLiteDatabase mydb; 

    private final Context myContext; 

    /** 
    * Constructor 
    * Takes and keeps a reference of the passed context in order to access to the application assets and resources. 
    * @param context 
    */ 
    public DataBaseHelper(Context context) { 

     super(context, DB_NAME, null, DB_VERSION); 
     this.myContext = context; 
     DB_PATH = "/data/data/" + context.getPackageName() + "/databases"; 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) {; 
    } 

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

public void apriDatabase() throws SQLException { 
    try { 
      String percorso = DB_PATH + DB_NAME; 
      mydb = SQLiteDatabase.openDatabase(percorso, null, SQLiteDatabase.OPEN_READONLY); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
} 

public void createDataBase() throws IOException{ 
    boolean dbExist = checkDataBase(); 
    if(dbExist){ 
      //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(); 
      } catch (IOException e) { 
        e.printStackTrace(); 
      } 
    } 
} 

private void copyDataBase() throws IOException{ 
    //Open your local db as the input stream 
    InputStream myInput = myContext.getAssets().open(DB_NAME); 
    // Path to the just created empty db 
    String outFileName = DB_PATH + DB_NAME; 

    // if the path doesn't exist first, create it 
    File f = new File(outFileName); 
    if (!f.exists()){ 
      f.mkdir(); 
      f.createNewFile(); 
    } 

    //Open the empty db as the output stream 
    OutputStream myOutput = new FileOutputStream(outFileName); 

    //transfer bytes from the inputfile to the outputfile 
    byte[] buffer = new byte[1024]; 
    int length; 
    while ((length = myInput.read(buffer))>0){ 
      myOutput.write(buffer, 0, length); 
    } 

    //Close the streams 
    myOutput.flush(); 
    myOutput.close(); 
    myInput.close(); 

} 

private boolean checkDataBase(){ 

    SQLiteDatabase checkDB = null; 

    try{ 
      String myPath = DB_PATH + DB_NAME; 
      checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); 

    }catch(SQLiteException e){ 

      //database does't exist yet. 

    } 

    if(checkDB != null){ 

      checkDB.close(); 

    } 

    return checkDB != null ? true : false; 
} 

@Override 
    public synchronized void close() { 
     if(mydb != null) 
      mydb.close(); 
     super.close(); 
    } 

}

questa è la listview che utilizza questa classe:

import android.app.ListActivity; 
import android.content.Intent; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleCursorAdapter; 

public class abicabList extends ListActivity { 

     protected EditText searchText; 
     protected SQLiteDatabase mydb; 
     protected Cursor cursor; 
     protected ListAdapter adapter; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     mydb = (new DataBaseHelper(this)).getWritableDatabase(); 
     searchText = (EditText) findViewById (R.id.searchText); 
    } 

    public void search(View view) { 

    String text = searchText.getText().toString(); 
    String cap = "CAP"; 
    // || is the concatenation operation in SQLite 
     if (text.length()14) {  
cursor = mydb.rawQuery("SELECT _id, ABI, BANCA, CAB, CAP, Filiale, City FROM abicab WHERE ABI || CAB LIKE ? LIMIT 30", 
      new String[]{"%" + searchText.getText().toString().substring(6,10) + "%" + searchText.getText().toString().substring(11,15) + "%"});  
    adapter = new SimpleCursorAdapter( 
           this, 
           R.layout.abicab_list_item, 
           cursor, 
           new String[] {"BANCA", "Filiale", "City", "CAP"}, 
       new int[] {R.id.BANCA, R.id.Filiale, R.id.City ,R.id.CAP}); 
     setListAdapter(adapter); 
    } 

    }

Così, quando eseguo l'applicazione del db viene creato nel cartella ma non contiene la tabella tha t è nel db che ho nella cartella delle risorse (vedi l'immagine [1]: http://i.stack.imgur.com/AaFj8.jpg). Grazie in anticipo per il vostro aiuto.

risposta

3

Ho risolto il problema.

1) Ho utilizzato la classe AlmanacSQLiteDatabaseAdapter.java utilizzata in Almanac 0.0.17 (progetto open source) che è possibile trovare qui: link. Puoi adattarti alle tue esigenze (nel mio caso l'ho ridenominato in DatabaseHelper);

2) Questa è la classe che utilizza l'Helper (è una listview che esegue la lettura rawquery di SQL in una stringa EditText - è un arrangiamento di questo tutorial "coenraets.org/blog/android-samples/androidtutorial/" :

public class MiaList extends Activity { 

     protected EditText searchText; 
     protected SQLiteDatabase db; 
     protected Cursor cursor; 
     protected ListAdapter ladapter; 
     protected ListView miaList; 
     private static final String DATABASE_NAME = "miodb.jpg"; 
/* 
L'ESTENSIONE JPG (o mp3, mov) questo perchè android ha il limite di 1 mb per i file di testo 
o simili nella asset, mentre NON HA limiti per i file multimediali! Nel mio caso si tratta di 4mb 
*/ 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

//qui sotto richiamo la classe DatabaseHelper 

     DatabaseHelper dbAdapter = DatabaseHelper.getInstance(this, DATABASE_NAME); 
     /*note di Vytek*/ 
     // OK Dovrei usare aSQLiteDatabaseAdapter.getDatabase(); ma questo crea 
     // problemi nella fase di OnPause quando premo Back cosi' invece non 
     // ottengo errori 
     // e viene fatta la normale copia del DB (13/8/2010 23.18) 
     // db = aSQLiteDatabaseAdapter.getWritableDatabase(); 
     // Per ovviare a questo problema controllo se e' la prima volta che 
     // chiamo applicazione 
     if (getFirstRun()) { 
       db = dbAdapter.getDatabase(); 
       setRunned(); 
     } else { 
       db = dbAdapter.getWritableDatabase(); 
     } 

     searchText = (EditText) findViewById (R.id.searchText); 
     miaList = (ListView) findViewById (R.id.list); 
    } 


    private void setRunned() { 
       // TODO Auto-generated method stub 

     } 

     private boolean getFirstRun() { 
       // TODO Auto-generated method stub 
       return false; 
     } 

     public void search(View view) { 

     String text = searchText.getText().toString(); 
     // || è l'operatore "concatena" in SQLite 
     if (text.length()<15){ 
        cursor = db.rawQuery("SELECT *FROM miatable WHERE AAA || ' ' || BBB || ' ' || CCC LIKE ? LIMIT 30", 
          new String[]{"%" + searchText.getText().toString() + "%"}); 
           ladapter = new SimpleCursorAdapter( 
               this, 
               R.layout.mialist_list_item, 
               cursor, 
               new String[] {"_id", "AAA", "BBB", "CCC"}, 
               new int[] {R.id._id, R.id.AAA, R.id.BBB, R.id.CCC}); 
           miaList.setAdapter(ladapter); 
           //istruzione da eseguire 
       } 
     else {   
        cursor = db.rawQuery("SELECT * FROM miatable WHERE AAA || BBB LIKE ? LIMIT 30", 
          new String[]{"%" + searchText.getText().toString().substring(6,10) + "%" + searchText.getText().toString().substring(11,15) + "%"});   
           ladapter = new SimpleCursorAdapter( 
               this, 
               R.layout.mialist_list_item, 
               cursor, 
               new String[] {"_id", "AAA", "BBB", "CCC"}, 
               new int[] {R.id._id, R.id.AAA, R.id.BBB, R.id.CCC}); 
           miaList.setAdapter(ladapter); 
           //istruzione da eseguire 
        } 


     } 

} 

Naturalmente il "miodb.jpg" SQLite dB deve essere nella cartella di asset di lavoro di Eclipse

PS ho usato estensione jpg per il db beacause la cartella risorsa ha. un limite di 1 Mb per l'estensione db o txt o xml.

2

Si sta utilizzando l'emulatore o il dispositivo?

Faccio la stessa procedura ma copio il database nella scheda SD, perché l'emulatore ha uno spazio limitato, qual è la dimensione del database?


Sostituisci il tuo metodo di copia con questo, e vorrei sapere perché non riuscivo a trovare nulla di strano se non il metodo di copia, Buona fortuna.

private void copyDataBase() throws IOException{ 

    //Open your local db as the input stream 
    InputStream myInput = myContext.getAssets().open(DB_NAME); 

    // Path to the just created empty db 
    String outFileName = DB_PATH + DB_NAME; 

    //Open the empty db as the output stream 
    OutputStream myOutput = new FileOutputStream(outFileName); 

    //transfer bytes from the inputfile to the outputfile 
    byte[] buffer = new byte[1024]; 
    int length; 
    while ((length = myInput.read(buffer))>0){ 
     myOutput.write(buffer, 0, length); 
    } 

    //Close the streams 
    myOutput.flush(); 
    myOutput.close(); 
    myInput.close(); 

} 
+0

L'emulatore. Il problema non è la dimensione ma la copia. Infatti se dai un'occhiata alla foto che ho collegato, verificherò cosa intendo. – Giumazzi

+0

L'emulatore. Il problema non è la dimensione ma la copia. Infatti se dai un'occhiata alla foto che ho collegato, verificherò cosa intendo. Tuttavia, se vuoi pubblicare come hai risolto il tuo codice, sarò molto contento. Il mio indirizzo è giumazzi (at) gmail com. – Giumazzi

+0

Si prega di consultare l'aggiornamento. –

0

Ecco il codice semplice e conveniente che uso:

public class DataBaseImportHelper { 
    private DataBaseImportHelper() {}; // Avoid instantiation 

/** 
* Creates a empty database on the system and rewrites it with your own database. 
*/ 
public static boolean importDataBase(Context context) { 
    InputStream myInput = null; 
    OutputStream myOutput = null; 
    try { 
     // Open local db from assets as the input stream 
     myInput = context.getAssets().open(DATABASE_NAME); 
     createEmptyDatabase(context); // See this method below 
     // Open the empty db as the output stream 
     myOutput = new FileOutputStream(getDatabaseFile(context)); 

     // transfer bytes from the inputfile to the outputfile 
     byte[] buffer = new byte[1024]; 
     int length; 
     while ((length = myInput.read(buffer)) > 0) { 
      myOutput.write(buffer, 0, length); 
     } 

     // Close the streams 
     myOutput.flush(); 
     myInput.close(); 
     myOutput.close(); 
     return true; 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return false; 
} 

/** 
* Check if the database already exists. 
* @return true if it exists, false if it doesn't 
*/ 
public static boolean isDatabaseExists(Context context) { 
    return getDatabaseFile(context).exists(); 
} 

private static File getDatabaseFile(Context context) { 
    return context.getDatabasePath(DatabaseHelper.DATABASE_NAME); 
} 

/** 
* Create an empty database into the default application database 
* folder.So we are gonna be able to overwrite that database with our database 
*/ 
private static void createEmptyDatabase(Context context) { 
      // use anonimous helper to create empty database 
    new SQLiteOpenHelper(context, DatabaseHelper.DATABASE_NAME, null, 1) { 
        // Methods are empty. We don`t need to override them 
     @Override 
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     } 

     @Override 
     public void onCreate(SQLiteDatabase db) { 
     } 
    }.getReadableDatabase().close(); 
} 

}

E l'utilizzo in codice:

if(!DataBaseImportHelper.isDatabaseExists(this)){ 
    if (!DataBaseImportHelper.importDataBase(this)){ 
      throw new IllegalStateException("Database doesn`t exist and hasn`t been copied!"); 
    } 
} 
2

prima di tutto assicurarsi di aggiungere android.permission .WRITE_EXTERNAL_STORAGE permesso per il tuo file manifest. In una delle mie app ho usato la classe qui sotto e funziona perfettamente. Prova questo e fammi sapere se funziona.

public class ImpotDatabaseFileTask extends AsyncTask<String, Void, Boolean> { 
ProgressDialog dialog; 
private Context con; 
boolean success = false; 

public ImpotDatabaseFileTask(Context con) { 
    this.con = con; 
    dialog = new ProgressDialog(con); 
    this.dialog.setMessage("Importing database..."); 
    execute(null); 
} 

@Override 
protected Boolean doInBackground(String... params) { 
    try { 
     OutputStream myOutput; 
     File destination = new File(Environment.getDataDirectory() 
       + "//data//<package name>//databases//database_name.db"); 

     // Set the folder on the SDcard 
     File dbFile = new File(Environment.getExternalStorageDirectory(), 
       "//<custom folder>//<database_name>.db"); 
     if (dbFile.exists()) { 
      copyFile(dbFile, destination); 
      success = true; 
     } 

    } catch (FileNotFoundException e) { 
     // Toast.makeText(Settings.this, 
     // "Restore unsuccessful! File not found! Directory does not exist?", 
     // Toast.LENGTH_LONG).show(); 

     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     Toast.makeText(con, "Restore unsuccessful!", Toast.LENGTH_SHORT) 
       .show(); 

     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return null; 
} 

void copyFile(File src, File dst) throws IOException { 
    FileChannel inChannel = new FileInputStream(src).getChannel(); 
    FileChannel outChannel = new FileOutputStream(dst).getChannel(); 
    try { 
     inChannel.transferTo(0, inChannel.size(), outChannel); 
    } finally { 
     if (inChannel != null) 
      inChannel.close(); 
     if (outChannel != null) 
      outChannel.close(); 
    } 
} 

@Override 
protected void onPostExecute(Boolean result) { 
    if (this.dialog.isShowing()) { 
     this.dialog.dismiss(); 
    } 
    if (success) { 
     Toast.makeText(con, "Restore successful!", Toast.LENGTH_SHORT) 
       .show(); 
    } else { 
     Toast.makeText(con, "Restore failed", Toast.LENGTH_SHORT).show(); 
    } 
    super.onPostExecute(result); 
} 

}

Problemi correlati