简体   繁体   English

Viewmodel 没有从 Android Room 更新数据,但成功插入其中

[英]Viewmodel doesn't update data from Android Room, but successfully insert in it

I try to understand the Room persistence library with this course , however, I stuck with updating RecyclerView and populate it with data in Room.我尝试通过本课程了解 Room 持久性库,但是,我坚持更新 RecyclerView 并用 Room 中的数据填充它。 Sorry for this boilerplate code.对不起这个样板代码。 Data passing to Room successfully and kept there as Android Database Inspector show to me, but at the same time, Rycyclerview is empty.数据成功传递到 Room 并保存在那里,如 Android Database Inspector 向我显示的那样,但同时,Rycyclerview 是空的。 Here is my code:这是我的代码:
Item:物品:

@Entity (tableName = "active_accounts")
public class Dashboard_Account {

    @PrimaryKey (autoGenerate = true)
    int accountID;

    @ColumnInfo(name = "accountName")
     String accountName;

    @ColumnInfo(name = "accountEmail")
     String accountEmail;

    public Dashboard_Account() {

    }

    public Dashboard_Account(String accountName,String accountEmail) {
        this.accountName = accountName;
        this. accountEmail = accountEmail;
    }

//getters and setters

DAO

@Dao
public interface Dashboard_DAO {

    @Insert (onConflict = OnConflictStrategy.REPLACE)
    void insert(Dashboard_Account... dashboard_accounts);

    @Delete
     void delete(Dashboard_Account account);

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

    @Update
     void update(Dashboard_Account account);

    @Query("SELECT * FROM active_accounts" )
    LiveData<List<Dashboard_Account>> getAllAccounts();
}

Database数据库

@Database(entities = {Dashboard_Account.class},version = 2,exportSchema = false)
public abstract class Dashboard_Database extends RoomDatabase {
        public abstract Dashboard_DAO dashboard_dao();

        private static Dashboard_Database INSTANCE;

        public static Dashboard_Database getDatabase(final Context context) {
                if (INSTANCE == null) {
                        synchronized (Dashboard_Database.class) {
                                if (INSTANCE == null) {
                                        INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                                                Dashboard_Database.class, "account_database")
                                                .fallbackToDestructiveMigration()
                                                .build();
                                }
                        }
                }
                return INSTANCE;
        }
}

Repository class存储库 class

public class Dashboard_Repository {
    private Dashboard_DAO mDashboardDao;
    private LiveData<List<Dashboard_Account>> mAllAccounts;

    Dashboard_Repository(Application application) {
        Dashboard_Database db = Dashboard_Database.getDatabase(application);
        mDashboardDao = db.dashboard_dao();
        mAllAccounts = mDashboardDao.getAllAccounts();
    }

    LiveData<List<Dashboard_Account>> getAllAcounts(){
        return mAllAccounts;
    }

    public void insert (Dashboard_Account account) {
        new insertAsyncTask(mDashboardDao).execute(account);
    }

    private static class insertAsyncTask extends AsyncTask<Dashboard_Account, Void, Void> {

        private Dashboard_DAO mAsyncTaskDao;

        insertAsyncTask(Dashboard_DAO mDashboardDao) {
            mAsyncTaskDao = mDashboardDao;
        }

        @Override
        protected Void doInBackground(final Dashboard_Account... params) {
            mAsyncTaskDao.insert(params[0]);
            return null;
        }
    }

Viewmodel视图模型

public class Dashboard_ViewModel extends AndroidViewModel {
    private Dashboard_Repository mRepo;
    private LiveData<List<Dashboard_Account>> mAllAccounts;


    public Dashboard_ViewModel(@NonNull Application application) {
        super(application);
        mRepo = new Dashboard_Repository(application);
        mAllAccounts = mRepo.getAllAcounts();
    }

    LiveData<List<Dashboard_Account>> getmAllAccounts() { return mAllAccounts; }
    public void insert(Dashboard_Account account) { mRepo.insert(account); }
}

For adding data I use DialogFragment with setFragmentResultListener that placed in Fragment onViewCreated()为了添加数据,我使用 DialogFragment 和 setFragmentResultListener 放置在 Fragment onViewCreated()

public class Dashboard_Fragment extends Fragment {
…
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
setRecyclerView();
getParentFragmentManager().setFragmentResultListener("fragmentKey", getViewLifecycleOwner(), (requestKey, result) -> {
       String name = result.getString("nameResult");
       String email = result.getString ("email");

       Dashboard_Account account = new Dashboard_Account(name,email);
       dashboardViewModel.insert(account);
});
}

And the code of recyclerview setup:以及recyclerview设置的代码:

private void setRecyclerView(){
    binding.accountView.setLayoutManager(new LinearLayoutManager(requireContext()));
    adapter = new Dashboard_RecyclevrViewAdapter(AccountItemList);
    dashboardViewModel.getmAllAccounts().observe(requireActivity(), accounts -> {
        adapter.setListContent(AccountItemList);
    });
    binding.accountView.setAdapter(adapter);
}

RecyclerViewAdapter is typical and here onBindViewHolder and setListcontent: RecyclerViewAdapter 是典型的,这里是 onBindViewHolder 和 setListcontent:

public class Dashboard_RecyclevrViewAdapter extends RecyclerView.Adapter<Dashboard_RecyclevrViewAdapter.MyViewHolder>  {
....
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
    if(pad_list!=null){
        final Dashboard_Account account  = pad_list.get(position);
        
        holder.binding.accountType.setText(account.getAccountName());
        holder.binding.acountemail.setText(account.getAccountValue()));
    }

}
…
public void setListContent(List <Dashboard_Account> pad_list) {
    this.pad_list = pad_list;
    notifyItemChanged(getItemCount());
}
….
}

I am really can't understand why the recycler view doesn't show data after I add the item to ViewModel, that in theory should handle with that.我真的不明白为什么在我将项目添加到 ViewModel 后回收站视图不显示数据,理论上应该处理。 I will provide additional code if it will be needed.如果需要,我会提供额外的代码。 Thanks in advance.提前致谢。

public void setListContent(List <Dashboard_Account> pad_list) {
    this.pad_list = pad_list;
    notifyItemChanged(getItemCount());
}

could be wrong but i don't really see the point of doing notifyItemChanged here, try adding in notifyDataSetChanged() instead可能是错的,但我真的不明白在这里做notifyItemChanged的意义,尝试添加notifyDataSetChanged()


notifyItemChanged tells the recycler that a specific item has been changed, while notifyDataSetChanged informs the recycler that all the data has (potentially) changed, this forces it to rebind all the items it has. notifyItemChanged告诉回收器某个特定项目已更改,而notifyDataSetChanged通知回收器所有数据已(可能)更改,这会强制它重新绑定它拥有的所有项目。

From the course you've mentioned, there's no reference to notifyItemChanged , so i'm not sure why you added it:)从您提到的课程中,没有提到notifyItemChanged ,所以我不确定您为什么添加它:)

the course link you've provided has:您提供的课程链接有:

void setWords(List<Word> words){
       mWords = words;
       notifyDataSetChanged(); <-- notifyDataSetChanged, not itemChanged
   }

Besides notifyDataSetChanged() that pointed out by @a_local_nobody you need to send the updated list to the RecyclerView adapter, not the original list除了notifyDataSetChanged()之外,您还需要将更新后的列表发送到RecyclerView适配器,而不是原始列表

To do that replace dapter.setListContent(AccountItemList);为此,请替换dapter.setListContent(AccountItemList); with dapter.setListContent(accounts);使用dapter.setListContent(accounts); in setRecyclerView()setRecyclerView()

private void setRecyclerView(){
    binding.accountView.setLayoutManager(new LinearLayoutManager(requireContext()));
    adapter = new Dashboard_RecyclevrViewAdapter(AccountItemList);
    dashboardViewModel.getmAllAccounts().observe(requireActivity(), accounts -> {
        adapter.setListContent(accounts); // <<< Change here
    });
    binding.accountView.setAdapter(adapter);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM