1

我有一个问题。“强制停止”后,我的数据库变为空。最初我打开空数据库,然后我正在添加一些数据。然后我在数据库中看到它们,它们可以在程序中看到。但是,如果我重新启动手机或“强制停止”应用程序 - 一切都从头开始。

这是我的DataBaseFactory代码:

package com.st.nyam.factories;

公共类数据库工厂 {

private SQLiteDatabase db;
private final Context context;
private SD_util sdUtil;
private static String DB_NAME = "nyam_db.db3";
private static String DB_PATH = "/data/data/com.st.nyam/databases/";    
private static String TAG = "DataBaseFactory";
//private final String INSERT_RECEPY = "INSERT into RECEPIES ('id', 'recepy', 'author') VALUES (?, ?, ?)";

private final String SELECT_RECIPES = "SELECT * FROM recipes";
private final String SELECT_RECIPE_BY_ID = "SELECT * FROM recipes WHERE ID = ?";
private final String SELECT_COUNT_RECIPE_BY_ID = "SELECT count(*) FROM recipes WHERE ID = ?";
private final String SELECT_STEPS = "SELECT * FROM steps";
private final String SELECT_TABLES = "SELECT name FROM sqlite_master WHERE type= 'table' ORDER BY name";
private final String SELECT_STEPS_BY_ID = "SELECT * FROM steps where recipe_id = ?";
private final String INSERT_STEP = "INSERT INTO steps ('id', 'recipe_id', 'body', 'photo_file_name') VALUES (?,?,?,?) ";
private final String INSERT_RECIPE = "INSERT INTO recipes ('id', 'title', 'description', 'user_id', 'favorites_by', 'main_photo_file_name') VALUES (?,?,?,?,?,?) ";

public DataBaseFactory(Context ctx) {
    context = ctx;  
    sdUtil = new SD_util();
    SQLiteDatabase temp_db = ctx.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
    temp_db.close();
    try {
        Log.i(TAG, "Copy intenting");
        copyDataBase();
    } catch (IOException e) {
        Log.e(TAG, e.getMessage());
    }
    Log.i(TAG, "Temp created");
    if (db == null) {
        db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
    }
    Log.i(TAG, "Temp opened");
}


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.
        e.printStackTrace();
    }
    if(checkDB != null){
        checkDB.close();
    }
    return checkDB != null ? true : false;
}

public void openDataBase() throws SQLException {
    //Open the database
    String myPath = DB_PATH + DB_NAME;
    db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}



private void copyDataBase() throws IOException {
    //Open your local db as the input stream
    InputStream myInput = context.getAssets().open("db/" + 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);
    }
    Log.i(TAG, "Copy data");
    //Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
}



public ArrayList<RecipeGeneral> getRecipes() {
    ArrayList<RecipeGeneral> recipes = new ArrayList<RecipeGeneral>();
    Cursor c = db.rawQuery(SELECT_RECIPES, null);
    Log.d(TAG, "getRecipes()");
    if (c != null && c.getCount() > 0) {
        c.moveToFirst();
        do {
            Log.d(TAG, "Getting recipe");
            RecipeGeneral recipe = ModelUtil.getRecipeFromCursor(c);
            recipes.add(recipe);
            Log.d(TAG, "Getting recipe added");
        } while (c.moveToNext());

    }
    c.close();
    return recipes;
}

public ArrayList<Step> getStepsByRecipeId(int recipeId) throws ParseException {
    Log.d(TAG, "In getStepsByRecipe");
    ArrayList<Step> steps = new ArrayList<Step>();
    Cursor c = db.rawQuery(SELECT_STEPS_BY_ID, new String[]{ Integer.toString(recipeId) });
    Log.d(TAG, "Get Query getStepsByRecipe");
    try {
        if (c != null && c.getCount() > 0) {
            c.moveToFirst();
            do {
                Log.d(TAG, "Getting step getStepsByRecipe");
                Step step = ModelUtil.getStepFromCursor(c);
                steps.add(step);
                Log.d(TAG, "Getting step added getStepsByRecipe");
            } while (c.moveToNext());
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    c.close();
    return steps;

}


/*
public ArrayList<Step> getSteps() throws ParseException {
    ArrayList<Step> steps = new ArrayList<Step>();
    Cursor c = db.rawQuery(SELECT_STEPS, null);
    if (c != null && c.getCount() > 0) {
        c.moveToFirst();
        do {
            Step step = new Step();
            step.setId(c.getInt(c.getColumnIndex("id")));
            step.setRecipe_id(c.getInt(c.getColumnIndex("recipe_id")));
            step.setBody(c.getString(c.getColumnIndex("body")));
            step.setPhoto_file_name(c.getString(c.getColumnIndex("photo_file_name")));
            step.setPhoto_content_type(c.getString(c.getColumnIndex("photo_content_type")));
            step.setPhoto_file_size(c.getInt(c.getColumnIndex("photo_file_size")));
            step.setPhoto_updated_at(new SimpleDateFormat("yyyy.MM.dd G HH:mm:ss").parse(c.getString(c.getColumnIndex("photo_updated_at"))));
            step.setCreated_at(new SimpleDateFormat("yyyy.MM.dd G HH:mm:ss").parse(c.getString(c.getColumnIndex("created_at"))));
            step.setUpdated_at(new SimpleDateFormat("yyyy.MM.dd G HH:mm:ss").parse(c.getString(c.getColumnIndex("updated_at"))));
            step.setPhoto_processing(c.getInt(c.getColumnIndex("photo_processing")));
            steps.add(step);
        } while (c.moveToNext());
    }
    c.close();
    return steps;
}
*/

public ArrayList<Recipe> fetchRecipesByQuery(String query) throws ParseException {
    ArrayList<Recipe> recipes = new ArrayList<Recipe>();
    Cursor c =  db.query(true, "virt", null, "description " + " Match " + "'*" + query + "*'", null,
            null, null, null, null);
    try{ 
        Log.i(TAG, "Get Query");
        if (c != null && c.getCount() > 0) {
            c.moveToFirst();
            do {
                Log.i(TAG, "Getting recipe");
                //Recipe recipe = ModelUtil.getRecipeFromCursor(c);
                //recipes.add(recipe);
                Log.i(TAG, "Getting recipe added");
            } while (c.moveToNext());
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return recipes;
}

public void addRecipeToFavorites(Recipe recipe, Bitmap bitmap) {
    if (!isRecipeExists(recipe.getId())) {
        ArrayList<Step> steps = recipe.getSteps();
        Log.d(TAG,"Adding  recipe to favorites addRecipeToFavorites()");
        sdUtil.saveRecipeImage(bitmap, recipe.getImg_url());
        db.execSQL(INSERT_RECIPE, new String[] {
            Integer.toString(recipe.getId()), recipe.getTitle(),
            recipe.getDescription(), recipe.getUser(),
            Integer.toString(recipe.getFavorites_by()), recipe.getImg_url()
        });
        for (Step step : steps) {
            Object [] params = new Object[] {step.getImg_url()};
            new DownloadImageStep().execute(params);
            Log.d(TAG,"Adding step to favorites addRecipeToFavorites()");
            addStepToFavorites(step, recipe.getId());
        }
    } else {
        Log.d(TAG,"Recipe already added");
    }
}

public void addStepToFavorites(Step step, int recipe_id) {
    db.execSQL(INSERT_STEP, new String[]{
            Integer.toString(step.getNumber()), Integer.toString(recipe_id),
            step.getInstruction(), step.getImg_url(),
        });

}



/*
public void putRecepy(Recepy recepy) {
    db.execSQL(INSERT_RECEPY, new String[] 
                {Integer.toString(recepy.getId()),
                            recepy.getRecepy(), recepy.getAuthor()});
}
 */


public boolean isRecipeExists(int id) {
    Cursor c = db.rawQuery(SELECT_RECIPE_BY_ID,  new String[] 
            {Integer.toString(id)});
    try {
        Log.d(TAG, "isRecipeExists before c.movetoFirst()");
        if (c.moveToFirst()) {
            if (c != null && c.getCount() > 0) {
                Log.d(TAG, "Checking passed");
                //Recipe recipe = ModelUtil.getRecipeFromCursor(c);
                //Log.d(TAG, "RECIPEExists: "  + recipe.toString());
                return true;
            }
        } 
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return false;
}

private class DownloadImageStep extends AsyncTask<Object,Void,Object> {

    @Override
    protected Object  doInBackground(Object... o) {
        Bitmap outBitmap = null;
        try{   
            sdUtil.saveStepImage((String)o[0]);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return outBitmap;
    }
}

}

4

1 回答 1

0

覆盖 SQLiteOpenHelper 类的 onUpgrade() 方法并确保它为空。那是您的数据库可能已被删除的地方。

于 2012-05-28T13:26:56.137 回答