Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android Studio更新房间数据库中的数据_Android_Database_Android Recyclerview - Fatal编程技术网

Android Studio更新房间数据库中的数据

Android Studio更新房间数据库中的数据,android,database,android-recyclerview,Android,Database,Android Recyclerview,我正在尝试使用来自不同活动的新数据更新/覆盖回收器视图中的数据。我有在我的主要活动中更新的数据。基本上,我需要覆盖在转到其他活动之前单击的数据 如果我有数据的话 名称=金枪鱼 等 如果已更新,则存储在房间数据库中 这是我的主要活动代码 public class MainActivity extends AppCompatActivity implements RecipeListAdapter.OnItemClickListener { private static fi

我正在尝试使用来自不同活动的新数据更新/覆盖回收器视图中的数据。我有在我的主要活动中更新的数据。基本上,我需要覆盖在转到其他活动之前单击的数据

如果我有数据的话 名称=金枪鱼 等 如果已更新,则存储在房间数据库中 这是我的主要活动代码

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 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);

}
公共接口RecipeDao{
@查询(“按recipeId ASC从配方表顺序选择*)
LiveData GetAlphaporzedWords();
@插入(onConflict=OnConflictStrategy.IGNORE)
无效插入(配方);
@查询(“从配方表中删除”)
void deleteAll();
@更新(onConflict=OnConflictStrategy.REPLACE)
无效更新(配方);
}

您的更新方法不起作用,因为您正在创建新项目,而房间不知道您要更新哪个项目

所以您需要一个uniq标识符,比如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
    }
}

因此,您可以通过查看项目ID来匹配项目,因为您正在创建新项目,而房间不知道要更新的项目,所以更新方法不起作用

所以您需要一个uniq标识符,比如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
    }
}

因此,您可以通过查看项目ID来匹配项目

您的插入方法工作但更新不工作,对吗?是的,您的更正您的插入方法工作但更新不工作,对吗?是的,您的更正您应该在配方对象中重写equals和hashcode方法您应该在配方对象中重写equals和hashcode方法