重启app后,Android SQLiteDatabase为空

时间:2012-05-31 11:22:37

标签: android sqlite

有人可以告诉我如何在重新启动应用程序后使我的数据库不为空: 现在,当我重新启动它时它就会空了。但我需要保存数据,即我插入。

我已经尝试过问这个问题,但是没有人告诉我我的错误。

这是我的代码:

public class DataBaseFactory   {

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 static int DATABASE_VERSION = 1;
// 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 (?,?,?,?,?,?) ";
private final String DELETE_RECIPE = "DELETE FROM recipes WHERE id = ?";
private final String DELETE_STEPS_BY_RECIPEID = "DELETE FROM steps WHERE recipe_id = ?";


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) {
    Log.d(TAG, "addRecipeToFavorites begin");
    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() });
        if (recipe.getSteps() != null) {
            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, "No steps in this recipe");
        }
    } else {
        Log.d(TAG, "Recipe already added");
    }
}



private 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 deleteRecipeFromFavorites(Recipe recipe) {
    Log.d(TAG, "deleteRecipeFromFavorites begin");
    if (isRecipeExists(recipe.getId())) {
        if (recipe.getSteps() != null) {
            for (Step step : recipe.getSteps()) {
                Log.d(TAG, "Boolean stepimage deleted = " + sdUtil.deleteImageFromSD(step.getImg_url().replace('/', '&')));
            }
            deleteStepsFromFavoritesByRecipeId(recipe.getId());
        } else {
            Log.d(TAG, "No steps in this recipe");
        }
        Log.d(TAG, "Image name in database = " + recipe.getImg_url().replace('/', '&'));
        Log.d(TAG, "Boolean recipeimage deleted = " + sdUtil.deleteImageFromSD(recipe.getImg_url().replace('/', '&')));
        Log.d(TAG, "Deleted rows: " + db.delete("recipes", "id=?", new String[] {Integer.toString(recipe.getId())}));
    } else {
        Log.d(TAG, "Recipe doesn`t exist");
    }
}

private void deleteStepsFromFavoritesByRecipeId(int recipeId) {
    Log.d(TAG, "deleteStepsFromFavoritesByRecipeId begin");
    db.delete("steps", "recipe_id=?", new String[] { Integer.toString(recipeId)});

}
/*
 * 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;
    }
}

}

更新: 我发现了自己的错误。它是在构造函数中。我不必创建temp_db并调用copyData();

1 个答案:

答案 0 :(得分:0)

我发现了自己的错误。它是在构造函数中。我不必创建temp_db并调用copyData();