[英]Android Studio updating data in Room Database
我正在嘗試使用來自不同活動的新數據更新/覆蓋我的回收站視圖中的數據。 我有在我的主要活動中從意圖更新的數據。 基本上我需要覆蓋在進入其他活動之前點擊的數據。
所以如果我有數據 Name = Tuna 等。如果它被更新,它會存儲在 Room 數據庫中 這是我的主要活動代碼
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);
}
您的更新方法不起作用,因為您正在創建新項目並且房間不知道您要更新哪個項目。
所以你需要一個像 id 和覆蓋方法這樣的 uniq 標識符
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
}
}
所以你可以通過查看它們的 id 來匹配項目
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.