2016-03-10 65 views
1

對於我的軟件工程類,我們必須將SQLite數據庫合併到我們的應用程序項目中。通過活動傳遞對象(Android)

對於我們的應用程序,這個數據庫類必須可以從多個活動訪問。我已經把數據庫定義爲單,然後調用

DBInterface database = Database.getInstance(this)

設置一個變量來引用數據庫,以訪問每個必要的類它的方法和它的作品。但是,我們應該在代碼中使用依賴注入,我的教授特意告訴我們,應該可以從我們的數據庫類切換到我們在前一次迭代中使用的存根數據庫,只需更改一行代碼即可。

顯然,這意味着要改變以上

DBInterface database = StubDB.getInstance(this)

但是在做這個我還是不得不在每一個使用數據庫的方法活動的這種變化。

所以我的問題是這樣的:有沒有辦法在我們的init活動中初始化我的數據庫,然後在沒有上面的賦值代碼的情況下傳遞對每個必要活動的引用?

相關代碼

辛格爾頓數據庫類

public class RecipeDatabase extends Activity implements DBInterface { 
    private dbHelper Helper; 
    private static RecipeDatabase sInstance; 
    private static Context sContext; 

    public static synchronized RecipeDatabase getInstance(Context context){ 
     if(sInstance == null){ 
      sInstance = new RecipeDatabase(context.getApplicationContext()); 
     } 
     return sInstance; 
    } 

    private RecipeDatabase(Context context){ 
     Helper = new dbHelper(context); 
     sContext = context; 
    } 

    @Override 
    public void addRecipe(Recipe recipe) 
    { 
     String ingredients = recipe.ingredientString(); 
     String directions = recipe.directionString(); 


     SQLiteDatabase db = Helper.getWritableDatabase(); 
     ContentValues values = new ContentValues(); 

     values.put(Recipe.KEY_rID, recipe.getrID()); 
     values.put(Recipe.KEY_mealtype, recipe.getMealType()); 
     values.put(Recipe.KEY_mainingredient, recipe.getMainIngredient()); 
     values.put(Recipe.KEY_description, recipe.getDescription()); 
     values.put(Recipe.KEY_ingredients, ingredients); 
     values.put(Recipe.KEY_directions, directions); 
     values.put(Recipe.KEY_notes, recipe.getNotes()); 
     values.put(Recipe.KEY_rating, recipe.getRating()); 
     values.put(Recipe.KEY_cooktime, recipe.getCooktime()); 

     db.insert(Recipe.TABLE, null, values); 

     db.close(); 
    } 

    @Override 
    public void editRecipe(Recipe recipe) 
    { 
     SQLiteDatabase db = Helper.getWritableDatabase(); 
     ContentValues values = new ContentValues(); 
     String ingredients = recipe.ingredientString(); 
     String directions = recipe.directionString(); 

     values.put(Recipe.KEY_rID, recipe.getrID()); 
     values.put(Recipe.KEY_mealtype, recipe.getMealType()); 
     values.put(Recipe.KEY_mainingredient, recipe.getMainIngredient()); 
     values.put(Recipe.KEY_description, recipe.getDescription()); 
     values.put(Recipe.KEY_ingredients, ingredients); 
     values.put(Recipe.KEY_directions, directions); 
     values.put(Recipe.KEY_notes, recipe.getNotes()); 
     values.put(Recipe.KEY_rating, recipe.getRating()); 
     values.put(Recipe.KEY_cooktime, recipe.getCooktime()); 

     db.update(Recipe.TABLE, values, Recipe.KEY_rID + " = ?", new String[]{String.valueOf(recipe.getrID())}); 
     db.close(); 
    } 

    @Override 
    public void deleteRecipe(Recipe recipe) 
    { 
     SQLiteDatabase db = Helper.getWritableDatabase(); 

     db.delete(Recipe.TABLE, Recipe.KEY_rID + " = ", new String[]{String.valueOf(recipe.getrID())}); 
     db.close(); 
    } 

    public ArrayList<Recipe> getList() 
    { 
     ArrayList<Recipe> result = new ArrayList<>(); 

     SQLiteDatabase db = Helper.getReadableDatabase(); 

     String selectQuery = "SELECT " + Recipe.KEY_rID + ", " + 
       Recipe.KEY_name + ", " + 
       Recipe.KEY_mealtype + ", " + 
       Recipe.KEY_mainingredient + ", " + 
       Recipe.KEY_description + ", " + 
       Recipe.KEY_ingredients + ", " + 
       Recipe.KEY_directions + ", " + 
       Recipe.KEY_notes + ", " + 
       Recipe.KEY_rating + ", " + 
       Recipe.KEY_cooktime + " FROM " + Recipe.TABLE; 

     Cursor cursor = db.rawQuery(selectQuery, null); 

     if(cursor.moveToFirst()) { 
      do { 
       ArrayList<String> ingredients = new ArrayList<>(); // Temp Storage 
       ArrayList<String> directions = new ArrayList<>(); // Temp Storage 

       String tempIngredient = cursor.getString(cursor.getColumnIndex(Recipe.KEY_ingredients)); 
       String[] temp = tempIngredient.split("- "); //Split up ingredients to individual strings 

       for(int x=0; x < temp.length; x++) { 
        ingredients.add(temp[x]); 
       } 

       String tempDirection = cursor.getString(cursor.getColumnIndex(Recipe.KEY_ingredients)); 
       temp = tempDirection.split("- ");//split up directions into individual strings 

       for(int x=0; x < temp.length; x++) { 
        directions.add(temp[x]); 
       } 
       //Get Values for Recipe Object 
       int rID = cursor.getInt(cursor.getColumnIndex(Recipe.KEY_rID)); 
       String name = cursor.getString(cursor.getColumnIndex(Recipe.KEY_name)); 
       String mealType = cursor.getString(cursor.getColumnIndex(Recipe.KEY_mealtype)); 
       String mainIngredient = cursor.getString(cursor.getColumnIndex(Recipe.KEY_mainingredient)); 
       int rating = cursor.getInt(cursor.getColumnIndex(Recipe.KEY_rating)); 
       String description = cursor.getString(cursor.getColumnIndex(Recipe.KEY_description)); 
       int cooktime = cursor.getInt(cursor.getColumnIndex(Recipe.KEY_cooktime)); 
       String notes = cursor.getString(cursor.getColumnIndex(Recipe.KEY_notes)); 

       //Create new Recipe from Row 
       Recipe tempRecipe = new Recipe(rID, name, description, mealType, mainIngredient, 
       rating, cooktime, notes, ingredients, directions); 

       //Add the recipe to the ArrayList 
       result.add(tempRecipe); 

      }while (cursor.moveToNext()); 
     } 
     //Return the populated ArrayList for use 
     return result; 
    } 
} 

初始化類

public class init extends ListActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_init); 

     //The code to change to switch from stub to database 
     DBInterface repository = RecipeDatabase.getInstance(this); 
     //DBInterface repository = new StubDB(this); 

     ArrayList<Recipe> recipes = repository.getList(); 
     ArrayList<String> recipeDisplay = new ArrayList<>(); 
     for(int i=0; i<recipes.size(); i++) { 
      recipeDisplay.add(recipes.get(i).getName()); 
     } 

     ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, recipeDisplay); 
     ListView lv = this.getListView(); 
     lv.setAdapter(myArrayAdapter); 
    } 

    @Override 
    protected void onListItemClick(ListView l, View v, int pos, long id){ 
     super.onListItemClick(l, v, pos, id); 

     Intent myIntent = new Intent(this, Details.class); 
     myIntent.putExtra("recipePosition", pos); 
     startActivity(myIntent); 
    } 

    public void shoppingListButton(View view){ 
     startActivity(new Intent(this, ShoppingList.class)); 
    } 

    public void addRecipeButton(View view){ 
     Intent myIntent = new Intent(this, Edit.class); 
     myIntent.putExtra("editType", 1); // 1 corresponds to add recipe 
     startActivity(myIntent); 
    } 
} 

一個需要的DB方法活動課

public class Details extends ListActivity { 
    int recipePosition = 0; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_details); 
     //want to avoid this call 
     DBInterface repository = RecipeDatabase.getInstance(this); 
     recipePosition = getIntent().getIntExtra("recipePosition", 0); 
     Recipe clickedRecipe = repository.getList().get(recipePosition); 
     ArrayList<String> recipeDetails = new ArrayList<>(); 
     recipeDetails.add(clickedRecipe.getName()); 
     recipeDetails.add(clickedRecipe.getDescription()); 
     recipeDetails.add("Ingredients:"); 
     for(int i=0; i<clickedRecipe.getIngredients().size(); i++){ 
      recipeDetails.add(clickedRecipe.getIngredients().get(i)); 
     } 
     recipeDetails.add("Instructions:"); 
     for(int i=0; i<clickedRecipe.getDirections().size(); i++){ 
      recipeDetails.add(clickedRecipe.getDirections().get(i)); 
     } 
     ArrayAdapter<String> myArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, recipeDetails); 
     ListView lv = this.getListView(); 
     lv.setAdapter(myArrayAdapter); 
    } 
    public void editButton(View view){ 
     Intent myIntent = new Intent(this, Edit.class); 
     myIntent.putExtra("recipePosition", recipePosition); 
     myIntent.putExtra("editType", 2); // 2 corresponds to modify recipe 
     startActivity(myIntent); 
    } 
} 

數據庫助手類

public class dbHelper extends SQLiteOpenHelper { 

    private static final int DATABASE_VERSION = 1; 

    private static final String DATABASE_NAME = "ROSE.db"; 

    public dbHelper(Context context){ 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db){ 
     //Creates the Recipe Table which stores recipes 
     String CREATE_TABLE_RECIPES = "CREATE TABLE " + Recipe.TABLE + 
       "(" + Recipe.KEY_rID + " INTEGER PRIMARY KEY, " + 
       Recipe.KEY_name + " TEXT, " + 
       Recipe.KEY_mealtype + " TEXT, " + 
       Recipe.KEY_mainingredient + " TEXT, " + 
       Recipe.KEY_description + " TEXT, " + 
       Recipe.KEY_ingredients + " TEXT, " + 
       Recipe.KEY_directions + " TEXT, " + 
       Recipe.KEY_notes + " TEXT, " + 
       Recipe.KEY_rating + " INTEGER, " + 
       Recipe.KEY_cooktime + " INTEGER)"; 
     db.execSQL(CREATE_TABLE_RECIPES); 
    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    { 
     db.execSQL("DROP TABLE IF EXISTS recipes"); 
     onCreate(db); 
    } 
} 
+0

在Android中搜索應用程序類的使用 –

回答

2

Dagger2對你來說是完美的。它非常易於使用,只需按照他們在文檔中提供的說明進行操作即可,一旦您找到答案,您一定會喜歡它。

基本上你要使用

@Inject 
DBInterface database; 

在每一次活動,片段,服務,或任何你想使用的數據庫。 然後你將創建一個DatabaseModule,它將有一個提供注入數據庫的方法。

@Singleton 
@Provides static DBInterface provideDatabase() { 
     return new WhateverDatabaseImplementsDBInterface(); 
} 

正如你所看到的,只是添加@Singleton將使它成爲一個單例。而現在改變你使用的數據庫確實是一個改變。

Dagger2是您肯定會遇到的依賴注入最大的問題,只需正確設置,如果您有任何問題(但不應該,請按照其詳細說明)編寫。

0

可以使用SQLiteOpenHelper。它將確保您的所有活動訪問相同的數據庫。即使您在每個Activity中都有不同的數據庫幫助程序對象,它們也都會訪問同一個數據庫。

+0

我有一個擴展了SQLiteOpenHelper的dbHelper類。我不太清楚我如何引用這個而不是RecipeDatabase對象。我編輯了我的問題以包含dbHelper類 – beelzabuddy

相關問題