SQLite资产数据库JAVA ANDROID

时间:2013-12-02 17:44:11

标签: android database sqlite assets sqliteopenhelper

我正在尝试从assets文件夹中获取sqlite数据库以在系统中创建新数据库,因此当您在设备上安装应用程序时,它会预加载一些数据 - 插入 - 和表格表格 - create table - 。 我创建了一个名为“SQLDataBase”的类,它从SQLiteOpenHelper扩展而来,它有以下主体:

public class SQLDataBase extends SQLiteOpenHelper {
public static final String KEY_TITULO = "titulo";
private static final String KEY_COD="id";
private static final String KEY_GENERO="genero";
private static final String KEY_DIRECTOR="director";
private static final String KEY_DURACION="duracion";
private static final String TABLA_BASEDATOS = "peliculas";
private SQLiteDatabase myDataBase;
private final Context myContext;
private static final String DATABASE_NAME = "peliculass"; 
public final static String DATABASE_PATH ="/data/data/com.bdsqlite/databases/";
public static final int DATABASE_VERSION = 1;

String sqlCreate ="create table peliculas (id integer primary key autoincrement, titulo text not null, director text not null,genero text not null, duracion int not null)";

public SQLDataBase(Context contexto) {
    super(contexto, DATABASE_NAME, null, DATABASE_VERSION);
    this.myContext = contexto;
}


public void createDatabase() throws IOException
{

      boolean dbExist = checkDataBase();

      if(dbExist)
      {
            Log.v("DB Exists", "db exists");
      }

      boolean dbExist1 = checkDataBase();
      if(!dbExist1)
      {
            this.getReadableDatabase();
            try
            {
                  this.close();    
                  copyDataBase();
            }
            catch (IOException e)
            {
                  throw new Error("Error copiando base de datos");
            }
      }

}

//Comprobamos si la base de datos existe ya
private boolean checkDataBase()
{
      boolean checkDB = false;
      try
      {
            String myPath = DATABASE_PATH + DATABASE_NAME;
            File dbfile = new File(myPath);
            checkDB = dbfile.exists();
      }
      catch(SQLiteException e)
      {
      }
      return checkDB;
}
//Copia la base de datos de la carpeta assets a la recien creada y vacia base de datos del sistema
private void copyDataBase() throws IOException
{
      String outFileName = DATABASE_PATH + DATABASE_NAME;

      OutputStream myOutput = new FileOutputStream(outFileName);
      InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

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

//elimina la base de datos
public void db_delete()
{
      File file = new File(DATABASE_PATH + DATABASE_NAME);
      if(file.exists())
      {
            file.delete();
            System.out.println("Base de datos eliminada.");
      }
}

//Abrir base de datos
public void openDatabase() throws SQLException
{
      String myPath = DATABASE_PATH + DATABASE_NAME;
      myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}

public synchronized void closeDataBase()throws SQLException
{
      if(myDataBase != null)
            myDataBase.close();
      super.close();
}

public void onCreate(SQLiteDatabase db)
{
}

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{    
      if (newVersion > oldVersion)
      {
            Log.v("Database Upgrade", "Database version higher than old.");
            db_delete();
      }
}


public void insertarContacto(String titulo, String director, String genero, int duracion) {
    ContentValues valoresIniciales = new ContentValues();
    valoresIniciales.put(KEY_TITULO, titulo);
    valoresIniciales.put(KEY_DIRECTOR, director);
    valoresIniciales.put(KEY_GENERO, genero);
    valoresIniciales.put(KEY_DURACION, duracion);

    //return db.insert(TABLA_BASEDATOS, null, valoresIniciales);
    myDataBase.execSQL("INSERT INTO peliculas(titulo,director,genero,duracion) VALUES (titulo,director,genero,duracion)");
}

 public Cursor obtenerTodasLasPeliculas() {
    return myDataBase.query(TABLA_BASEDATOS, new String[] { KEY_COD, KEY_TITULO,KEY_DIRECTOR,KEY_GENERO,KEY_DURACION}, null, null, null, null, null);
}
 public Cursor obtenerInfo(String nombre) {
     return myDataBase.query(TABLA_BASEDATOS,new String[] { KEY_DIRECTOR,KEY_GENERO,KEY_DURACION} , "titulo=?", new String[] { nombre }, null, null, null);

}

 public void cerrar() {
    myDataBase.close();
}

public Cursor obtenerPeliculasGenero(String genre) {

    return myDataBase.query(TABLA_BASEDATOS, new String[] { KEY_COD, KEY_TITULO,KEY_DIRECTOR,KEY_DURACION}, "genero=?", new String[]{ genre }, null, null, null);

}

public void EliminarPelicula(String titulo){
    myDataBase.execSQL("DELETE FROM peliculas WHERE titulo='"+titulo+"'");

}

public void ModificarPelicula(String titulo, String director, String genero, int duracion, String titulo2){
    myDataBase.execSQL("UPDATE peliculas SET titulo='"+titulo+"', director='"+director+"',genero='"+genero+"',duracion="+duracion+" WHERE titulo='"+titulo2+"'");

}
}

现在在我的主要班级:

SQLDataBase basededatos;
方法onCreate中的

basededatos=new SQLDataBase(this);
mostrarpelicula();

public void mostrarPeliculas(){
    cont=0;
     basededatos.getReadableDatabase();
     Cursor c=basededatos.obtenerTodasLasPeliculas();
    resultados=new String[c.getCount()];
     if (c.moveToFirst()) {
            do {

                DisplayFilm(c);
            } while (c.moveToNext());
        }

     basededatos.cerrar(); 
}

public void DisplayFilm(Cursor c) {

    resultados[cont]=c.getString(1);
    cont++; 

}

它实际上没有用,它说:

 java.lang.NullPointerException at "return myDataBase.query(TABLA_BASEDATOS,
 new String[] { KEY_COD, KEY_TITULO,KEY_DIRECTOR,KEY_GENERO,KEY_DURACION}, null, null, null, null, null);"

你能帮助我吗?

2 个答案:

答案 0 :(得分:0)

我的一个应用程序中有类似的设置,问题是我的数据库的名称。

尝试更改

private static final String DATABASE_NAME = "peliculass";

private static final String DATABASE_NAME = "peliculass.sqllite"; //or .sqllite3 or whatever the extension is

答案 1 :(得分:0)

如果您手上有 .db数据库,那么事情会容易得多。可以将.sqlite数据库转换为.db数据库。在您的应用程序首次启动安装后初始化SuperDatabase对象

mov eax, [esp+8]

对于后续的应用启动,请使用

SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.COPY_TO_SYSTEM);

现在只需触发你的非返回查询

SuperDatabase database=new SuperDatabase(getApplicationContext(),"foods.db", AssetDatabaseMode.READ_FROM_DEVICE);

如果您有一些返回类型查询,那么可以用CSV,JSON或XML格式获取结果。

作为CSV

database.sqlInject("INSERT INTO food VALUES('Banana','Vitamin A');");

或者作为JSON

ArrayList<String> rows=new ArrayList<String>();
rows=database.sqlEjectCSV("SELECT * FROM food;");
for (int i=0;i<rows.size();i++)
{
//Each row iterated with attribute values seperated by comma
}

或者作为XML

String json=database.sqlEjectJSON("SELECT * FROM food;");

要使用SuperDatabase,您需要将此添加到Gradle。以下是完整的文档:https://github.com/sangeethnandakumar/TestTube