salimdz Posté(e) 19 janvier 2013 Share Posté(e) 19 janvier 2013 Bonjour, je veux copier un base SQLite dans un provider, mais j'ai pas trouvé le bonne façon, j'ai essayé ce source mais il ne marche pas ta base reste vide, package dz.algerie.android.informationLite; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import android.content.*; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.provider.BaseColumns; import android.text.TextUtils; public class Provider extends ContentProvider { private static final String DATABASE_NAME = "walgerie.db"; private static String DATABASE_PATH = "/data/data/dz.algerie.android.informationLite/databases/"; private static String DATABASE_TABLE_BIENVENUE = "Bienvenue"; private static String DATABASE_TABLE_VERSION = "Version"; private static int DATABASE_VERSION = 9; private static final int CONSTANTS=1; private static final int CONSTANT_ID=2; private static final UriMatcher MATCHERBienvenue; private static final UriMatcher MATCHERVersion; private static HashMap<String, String> BIENVENUE_LIST_PROJECTION; private static HashMap<String, String> VERSION_LIST_PROJECTION; public static final class Bienvenue implements BaseColumns { public static final Uri CONTENT_URI =Uri.parse("content://dz.algerie.android.informationLite.Provider/bienvenue"); public static final String DEFAULT_SORT_ORDER_ID = "_id"; public static final String _ID = "_id"; public static final String BIENVENUE_EN = "Bienvenue_EN"; public static final String BIENVENUE_FR = "Bienvenue_FR"; } static { MATCHERBienvenue=new UriMatcher(UriMatcher.NO_MATCH); MATCHERBienvenue.addURI("dz.algerie.android.informationLite.Provider", "bienvenue", CONSTANTS); MATCHERBienvenue.addURI("dz.algerie.android.informationLite.Provider", "bienvenue/#", CONSTANT_ID); BIENVENUE_LIST_PROJECTION = new HashMap<String, String>(); BIENVENUE_LIST_PROJECTION.put(Provider.Bienvenue._ID, Provider.Bienvenue._ID); BIENVENUE_LIST_PROJECTION.put(Provider.Bienvenue.BIENVENUE_EN, Provider.Bienvenue.BIENVENUE_EN); BIENVENUE_LIST_PROJECTION.put(Provider.Bienvenue.BIENVENUE_FR, Provider.Bienvenue.BIENVENUE_FR); } public static final class Version implements BaseColumns { public static final Uri CONTENT_URI =Uri.parse("content://dz.algerie.android.informationLite.Provider/version"); public static final String DEFAULT_SORT_ORDER_ID = "_id"; public static final String _ID = "_id"; public static final String VERSIONCODE = "VersionCode"; } static { MATCHERVersion=new UriMatcher(UriMatcher.NO_MATCH); MATCHERVersion.addURI("dz.algerie.android.informationLite.Provider", "version", CONSTANTS); MATCHERVersion.addURI("dz.algerie.android.informationLite.Provider", "version/#", CONSTANT_ID); VERSION_LIST_PROJECTION = new HashMap<String, String>(); VERSION_LIST_PROJECTION.put(Provider.Version._ID, Provider.Version._ID); VERSION_LIST_PROJECTION.put(Provider.Version.VERSIONCODE, Provider.Version.VERSIONCODE); } public String getDbName() { return(DATABASE_NAME); } public int getDbVersion() { return(DATABASE_VERSION); } private class DatabaseHelper extends SQLiteOpenHelper { 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, DATABASE_NAME, null, DATABASE_VERSION); Log.v("Guide_DatabaseHelper", context.toString()); this.myContext = context; } @SuppressWarnings({ "unused" }) public void createDataBase() throws IOException{ boolean dbExist = checkDataBase(); Log.v("Guide_createDataBase", "createDataBase"); if(dbExist){ //do nothing - database already exist Log.v("Guide_createDataBase", "Exist Base"); }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. Log.v("Guide_createDataBase", "No Exist Base"); this.getReadableDatabase(); try { copyDataBase(); } catch (IOException e) { throw new Error("Error copying database"); } } } private boolean checkDataBase(){ SQLiteDatabase checkDB = null; boolean btCopyBases = false; Log.v("Guide_checkDataBase", "Entree"); try{ String myPath = DATABASE_PATH + DATABASE_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); if(checkDB != null){ Cursor c1=db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='"+DATABASE_TABLE_BIENVENUE+"'", null); Cursor c2=db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='"+DATABASE_TABLE_VERSION+"'", null); if (c1.getCount() == 0 || c2.getCount() == 0) { btCopyBases = true; Log.v("Guide_checkDataBase", "CopyBases_1"); } if (c2 != null && c2.getCount() == 1) { c2.moveToFirst(); int VersionCode = c2.getInt(c8.getColumnIndex("VersionCode")); if (VersionCode != 21) { btCopyBases = true; Log.v("Guide_checkDataBase", "CopyBases_2"); } } if (btCopyBases == true) checkDB = null; Log.v("Guide_checkDataBase", "CopyBases_3"); } }catch(SQLiteException e){ //database does't exist yet. } if(checkDB != null){ checkDB.close(); Log.v("Guide_checkDataBase", "Close"); } Log.v("Guide_checkDataBase", checkDB.toString()); return checkDB != null ? true : false; } private void copyDataBase() throws IOException{ //Open your local db as the input stream Log.v("Guide_copyDataBase", ""); InputStream myInput = myContext.getAssets().open(DATABASE_NAME); // Path to the just created empty db String outFileName = DATABASE_PATH + DATABASE_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(); } @SuppressWarnings("unused") public void openDataBase() throws SQLException{ //Open the database Log.v("Guide_openDataBase", ""); String myPath = DATABASE_PATH + DATABASE_NAME; db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); Log.v("Guide_openDataBase", db.toString()); } @Override public synchronized void close() { if(db != null) db.close(); Log.v("Guide_close", "db.close"); super.close(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub } } private SQLiteDatabase db; @Override public boolean onCreate() { db=(new DatabaseHelper(getContext())).getReadableDatabase(); Log.v("Guide_onCreate", db.toString()); return (db == null) ? false : true; } @Override public Cursor query(Uri url, String[] projection, String selection, String[] selectionArgs, String sort) { SQLiteQueryBuilder qb=new SQLiteQueryBuilder(); qb.setTables(getTableName(url)); if (isCollectionUri(url)) { qb.setProjectionMap(getDefaultProjection(url)); } else { qb.appendWhere(getIdColumnName()+"="+url.getPathSegments().get(1)); } String orderBy; if (TextUtils.isEmpty(sort)) { orderBy=getDefaultSortOrder(url); } else { orderBy=sort; } Cursor c=qb.query(db, projection, selection, selectionArgs, null, null, orderBy); c.setNotificationUri(getContext().getContentResolver(), url); return c; } @Override public String getType(Uri url) { if (isCollectionUri(url)) { return(getCollectionType()); } return(getSingleType()); } @Override public Uri insert(Uri url, ContentValues initialValues) { // return null; } @Override public int delete(Uri url, String where, String[] whereArgs) { // return 0; } @Override public int update(Uri url, ContentValues values, String where, String[] whereArgs) { // return 0; } private boolean isCollectionUri(Uri url) { if (url.toString() == Provider.Bienvenue.CONTENT_URI.toString()) { return(MATCHERBienvenue.match(url)==CONSTANTS); } else { if (url.toString() == Provider.Version.CONTENT_URI.toString()) { return(MATCHERVersion.match(url)==CONSTANTS); } else { return false; } } } } private HashMap<String, String> getDefaultProjection(Uri url) { if (url.toString() == Provider.Bienvenue.CONTENT_URI.toString()) { return(BIENVENUE_LIST_PROJECTION); } else { if (url.toString() == Provider.Version.CONTENT_URI.toString()) { return(VERSION_LIST_PROJECTION); } else { return(null); } } } } private String getTableName(Uri url) { if (url.toString() == Provider.Bienvenue.CONTENT_URI.toString()) { return(DATABASE_TABLE_BIENVENUE); } else { if (url.toString() == Provider.Version.CONTENT_URI.toString()) { return(DATABASE_TABLE_VERSION); } else { return(""); } } } } private String getIdColumnName() { return("_id"); } private String getDefaultSortOrder(Uri url) { if (url.toString() == Provider.Bienvenue.CONTENT_URI.toString()) { return(Provider.Bienvenue.DEFAULT_SORT_ORDER_ID); } else { if (url.toString() == Provider.Version.CONTENT_URI.toString()) { return(Provider.Version.DEFAULT_SORT_ORDER_ID); } else { return(""); } } } } } private String getCollectionType() { return("vnd.android.cursor.dir/vnd.algerie.informationLite"); } private String getSingleType() { return("vnd.android.cursor.item/vnd.algerie.informationLite"); } } j’attende votre aide merci d'avance bonne journée Citer Lien vers le commentaire Partager sur d’autres sites More sharing options...
Mitsuaki Posté(e) 29 janvier 2013 Share Posté(e) 29 janvier 2013 ça ne marche pas...soit... Mais ça te fait quoi comme erreur ? Tu as bien mis ta base de donnée (remplie) dans le répertoire assets ? J'avais mis un code plus ou moins similaire sur le forum. La démarche étant de checker la base en RO, et si elle n'existe pas, de faire un copie bits à bits de assets vers le répertoire de ton appli. (/data/data/ton-appli/databases/ par exemple) Perso, en regardant rapidement le code et vu l'intendation completement pétée, difficile de dire si il y a un soucis. Citer Lien vers le commentaire Partager sur d’autres sites More sharing options...
Recommended Posts
Rejoignez la conversation
Vous pouvez poster maintenant et vous enregistrez plus tard. Si vous avez un compte, connectez-vous maintenant pour poster.