Android Студия обновляет данные в Room Database - PullRequest
0 голосов
/ 02 апреля 2020

Я пытаюсь обновить / перезаписать данные в моем представлении переработчика новыми данными из другой деятельности. У меня есть данные, которые были обновлены в моей основной деятельности от намерения. В основном мне нужно перезаписать данные, по которым щелкнули, прежде чем перейти к другому виду деятельности.

Так что, если бы у меня были данные Name = Tuna et c. Если оно было обновлено, оно сохраняется в базе данных комнат. Вот мой основной код активности

public class MainActivity extends AppCompatActivity implements 
      RecipeListAdapter.OnItemClickListener  {
    private static final String TAG = "MAIN ACTIVITY";
    private static final int RESULT_UPDATED = 300;
    private RecipeViewModel mRecipeViewModel;
        public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
    public static final int UPDATE_WORD_ACTIVITY_REQUEST_CODE = 2;
        public String Name;
        public String Ingredients;
        public String Method;
        private RecipeListAdapter mAdapter;
        private RecipeDao recDao;
        Menu menu;
    List<Recipe> recipesList = new ArrayList<>();

    ListView search_items;

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);
            RecyclerView recyclerView = findViewById(R.id.recyclerview);
         mAdapter = new RecipeListAdapter(this);
            recyclerView.setAdapter(mAdapter);
            mAdapter.setOnItemClickListener(MainActivity.this);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            mRecipeViewModel = new ViewModelProvider(this).get(RecipeViewModel.class);

            Log.d(TAG, "SIZE OF LIST: "+ recipesList);
            mRecipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
                @Override
                public void onChanged(@Nullable final List<Recipe> recipes) {
                    // Update the cached copy of the words in the adapter.
                    int size = mAdapter.getItemCount();
                    Log.d(TAG, "List of List : " + recipes);
                    recipesList= recipes;
                    mAdapter.setWords(recipes);
                }
            });

            FloatingActionButton fab = findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(MainActivity.this, AddRecipeActivity.class);
                    startActivityForResult(intent, NEW_WORD_ACTIVITY_REQUEST_CODE);
                }
            });



    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "Result code = " + resultCode);
        super.onActivityResult(requestCode, resultCode, data);
      // else {
      //      Toast.makeText(
       ///             getApplicationContext(),
        //            R.string.empty_not_saved,
         //           Toast.LENGTH_LONG).show();
       // }
       switch (requestCode){
           case 1:
               Log.d(TAG, "Result code = " + resultCode);
               ArrayList<String> rData = data.getStringArrayListExtra(AddRecipeActivity.EXTRA_REPLY);
               String name = rData.get(0);
               String ingredients = rData.get(1);
               String method = rData.get(2);
               Recipe recipe = new Recipe(name, ingredients, method);
               RecipeViewModel.insert(recipe);
               break;
           case 2:
               ArrayList<String> uData = data.getStringArrayListExtra(UpdateRecipeActivity.EXTRA_REPLY);
               String nameUp = uData.get(0);
               String ingredientsUp = uData.get(1);
               String methodUp = uData.get(2);
               Log.d(TAG, "Name: " + nameUp.toString());
               Log.d(TAG, "ING: " + ingredientsUp.toString());
               Log.d(TAG, "Method: " + methodUp.toString());
               Recipe recipeUp = new Recipe(nameUp, ingredientsUp, methodUp);
                RecipeViewModel.update(recipeUp);
       }

    }

    @Override
    public void onItemClick(int position, View view) {
            Log.d(TAG, "onItemClick Position: " + position);
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setTitle("Edit or Delete...");
        alertDialog.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                recipesList.get(position); //clicked item
                Intent update = new Intent(MainActivity.this, UpdateRecipeActivity.class);
                update.putExtra("Name", recipesList.get(position).getName()); //
                update.putExtra("Ingredients", recipesList.get(position).getIngredients());
                update.putExtra("Method", recipesList.get(position).getMethod());
                startActivityForResult(update, UPDATE_WORD_ACTIVITY_REQUEST_CODE);

            }

        });
        alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //Delete

                Log.d(TAG, "List: " + recipesList);
                Log.d(TAG, "Index: " + position);
                int removeIndex = position;
                // recipesList.remove(removeIndex);
                mAdapter.deleteItem(removeIndex);


            }
        });
        alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        alertDialog.show();
    }
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.options_menu, menu);
            SearchView search = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.search));
           // SearchView search = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.search));
            // Associate searchable configuration with the SearchView
            SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
            search.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchResultActivity.class)));
            search.setQueryHint(getResources().getString(R.string.search_hint));
            return true;
        }

}

Вот код в модели представления для обновления

public static void update(Recipe recipe) { repo.update(recipe);}

Вот код в мой репо

public interface RecipeDao {


    @Query("SELECT * from recipe_table ORDER BY recipeId ASC")
    LiveData<List<Recipe>> getAlphabetizedWords();

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    void insert(Recipe recipe);

    @Query("DELETE FROM recipe_table")
    void deleteAll();

    @Update(onConflict = OnConflictStrategy.REPLACE)
    void update (Recipe recipe);

}

1 Ответ

2 голосов
/ 02 апреля 2020

Ваш метод обновления не работает, потому что вы создаете новый элемент, а комната не знает, какой элемент вы хотите обновить.

Поэтому вам необходим уникальный идентификатор, такой как методы id и override

data class Recipe(
    @PrimaryKey
    val id: Int?,
    val name: String?,
    val ing : String?,
    val method : Int?
) {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as Recipe

        if (id != other.id) return false

        return true
    }

    override fun hashCode(): Int {
        return id ?: 0
    }
}

Таким образом, вы можете сопоставить предметы, посмотрев их идентификаторы

...