Java 在MVVM体系结构中从存储库插入数据后,无法切换到MainActivity

Java 在MVVM体系结构中从存储库插入数据后,无法切换到MainActivity,java,android,rx-java2,Java,Android,Rx Java2,我正在为应用程序开发实施MVVM架构模式。我有两个活动MainActivity和AddUser活动。在MainActivity中,我显示所有注释的列表,在AddUser活动中,我在room数据库中插入用户。我正在执行所有插入和删除操作获取存储库类中的注释操作。我正在使用RxJava Completable操作符在数据库中插入注释 我想要什么:插入后,它应该重定向到MainActivity 问题:当我使用Intent时,无法在onComplete()方法中添加Intent,它显示错误 错误 Pro

我正在为应用程序开发实施MVVM架构模式。我有两个活动MainActivityAddUser活动。在MainActivity中,我显示所有注释的列表,在AddUser活动中,我在room数据库中插入用户。我正在执行所有插入和删除操作获取存储库类中的注释操作。我正在使用RxJava Completable操作符在数据库中插入注释

我想要什么:插入后,它应该重定向到MainActivity

问题:当我使用Intent时,无法在onComplete()方法中添加Intent,它显示错误

错误

Process: com.app.notesreactive, PID: 3970
io.reactivex.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with.
下面是我的代码:

UserDao.java

@Dao
public interface UserDao {

@Insert
void insert(User user);

@Query("SELECT * FROM Users ORDER BY id DESC")
LiveData<List<User>> getAllUsers();

}
public class UserRepository {

private UserDb userDb;
private UserDao userDao;
private LiveData<List<User>> allUsers;
private Context ctx;

public UserRepository(Application application) {

    userDb = UserDb.getInstance(application);
    userDao = userDb.userDao();
    allUsers = userDao.getAllUsers();
    ctx = application.getApplicationContext();
}

public void insert(final User user){

   Completable.fromAction(() -> userDb.userDao().insert(user))
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new CompletableObserver() {

                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onComplete() {

                                         Intent i = new Intent(ctx,MainActivity.class);
                                        ctx.startActivity(i);

                                        Toast.makeText(ctx,"Data inserted", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                       Toast.makeText(ctx,e.getMessage(),Toast.LENGTH_SHORT).show();
                                    }
                                });

      }

   public LiveData<List<User>> getAllUsers(){

       return allUsers;
    }

  }       
@Dao
公共接口UserDao{
@插入
无效插入(用户);
@查询(“按id描述从用户订单中选择*)
LiveData getAllUsers();
}
UserRepository.java

@Dao
public interface UserDao {

@Insert
void insert(User user);

@Query("SELECT * FROM Users ORDER BY id DESC")
LiveData<List<User>> getAllUsers();

}
public class UserRepository {

private UserDb userDb;
private UserDao userDao;
private LiveData<List<User>> allUsers;
private Context ctx;

public UserRepository(Application application) {

    userDb = UserDb.getInstance(application);
    userDao = userDb.userDao();
    allUsers = userDao.getAllUsers();
    ctx = application.getApplicationContext();
}

public void insert(final User user){

   Completable.fromAction(() -> userDb.userDao().insert(user))
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new CompletableObserver() {

                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onComplete() {

                                         Intent i = new Intent(ctx,MainActivity.class);
                                        ctx.startActivity(i);

                                        Toast.makeText(ctx,"Data inserted", Toast.LENGTH_SHORT).show();
                                    }

                                    @Override
                                    public void onError(Throwable e) {

                                       Toast.makeText(ctx,e.getMessage(),Toast.LENGTH_SHORT).show();
                                    }
                                });

      }

   public LiveData<List<User>> getAllUsers(){

       return allUsers;
    }

  }       
公共类用户存储库{
私有用户数据库;
私有UserDao UserDao;
私有LiveData用户;
私有上下文ctx;
公共用户存储库(应用程序){
userDb=userDb.getInstance(应用程序);
userDao=userDb.userDao();
allUsers=userDao.getAllUsers();
ctx=application.getApplicationContext();
}
公共作废插入(最终用户){
Completable.fromAction(()->userDb.userDao().insert(user))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.订阅(新的CompletableObserver(){
@凌驾
认购的公共无效(一次性d){
}
@凌驾
未完成的公共空间(){
意向i=新意向(ctx,MainActivity.class);
星触觉(i);
Toast.makeText(ctx,“插入数据”,Toast.LENGTH_SHORT.show();
}
@凌驾
公共无效申报人(可丢弃的e){
Toast.makeText(ctx,e.getMessage(),Toast.LENGTH_SHORT.show();
}
});
}
公共LiveData getAllUsers(){
回归诱惑;
}
}       
有人请帮助我如何才能达到预期的结果。任何帮助将不胜感激


谢谢

从repository类切换活动我们需要向Intent添加以下标志。 下面是一个更新的onComplete()方法

希望这会有所帮助


谢谢

从repository类切换活动我们需要向Intent添加以下标志。
Process: com.app.notesreactive, PID: 3970
io.reactivex.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with.
下面是一个更新的onComplete()方法

希望这会有所帮助


谢谢

在存储库中启动活动不是一个好做法。您需要在活动中启动活动。如果要使用应用程序上下文启动活动,应使用
Intent.FLAG\u activity\u NEW\u TASK
。导致使用默认标志从应用程序的
上下文启动活动会阻止活动的后堆栈(层次结构)。我建议使用RxJava的
Observable
LiveData
之类的可观察对象来通知活动,并在其上启动另一个活动。如何使用
LivaData

Process: com.app.notesreactive, PID: 3970
io.reactivex.exceptions.UndeliverableException: The exception could not be delivered to the consumer because it has already canceled/disposed the flow or the exception has nowhere to go to begin with.
更新了
insert
方法,如下所示:

public LiveData<Boolean> insert(final User user){
    MutableLiveData<Boolean> isComplated = new MutableLiveData<>();

    Completable.fromAction(() -> userDb.userDao().insert(user))
    .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new CompletableObserver() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onComplete() {
                isComplated.setValue(true);
                Toast.makeText(ctx,"Data inserted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable e) {
                Toast.makeText(ctx,e.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    return isComplated;
}
编辑: ViewModel类应包含以下方法:

public LiveData<Boolean> insert(User user) {
    return userRepositoryInstance.insert(user);
}
public-LiveData插入(用户){
返回userRepositoryInstance.insert(用户);
}

它应该有帮助=)

在存储库中启动一个活动不是好的做法。您需要在活动中启动活动。如果要使用应用程序上下文启动活动,应使用
Intent.FLAG\u activity\u NEW\u TASK
。导致使用默认标志从应用程序的
上下文启动活动会阻止活动的后堆栈(层次结构)。我建议使用RxJava的
Observable
LiveData
之类的可观察对象来通知活动,并在其上启动另一个活动。如何使用
LivaData

更新了
insert
方法,如下所示:

public LiveData<Boolean> insert(final User user){
    MutableLiveData<Boolean> isComplated = new MutableLiveData<>();

    Completable.fromAction(() -> userDb.userDao().insert(user))
    .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new CompletableObserver() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onComplete() {
                isComplated.setValue(true);
                Toast.makeText(ctx,"Data inserted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Throwable e) {
                Toast.makeText(ctx,e.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
    return isComplated;
}
编辑: ViewModel类应包含以下方法:

public LiveData<Boolean> insert(User user) {
    return userRepositoryInstance.insert(user);
}
public-LiveData插入(用户){
返回userRepositoryInstance.insert(用户);
}


这应该会有帮助=)

您没有遵循正确的MVVM体系结构。尝试从viewmodel调用存储库的方法,并使用实时数据通知视图(活动)。您收到了什么错误?是的,我正在使用viewmodel调用方法并从viewmodel更新UI。在viewmodel中使用subscribe和observe,而不是在存储库类中。我已更新了我的帖子A,并在修改onComplete()后方法它正在显示上面发布的错误。您没有遵循正确的MVVM体系结构。尝试从viewmodel调用存储库的方法,并使用实时数据通知视图(活动)。您收到了什么错误?是的,我正在使用viewmodel调用方法并从viewmodel更新UI。在viewmodel中使用subscribe和observe,而不是在存储库类中。我已更新了我的帖子A,并在修改onComplete()后方法它显示了上面发布的错误。我是否需要更新Dao insert方法,因为我有无效的insert(用户)。不需要这样做@DigVijay我的答案有任何问题,请让我知道,因为它工作正常。没有问题。但从MVVM体系结构的角度来看,这是错误的。执行视图操作不是存储库的责任。我是im