Android Live数据观察器异常 [英] Android Live data observer exception

本文介绍了Android Live数据观察器异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现新的android体系结构组件,并在片段和视图模型中使用了实时数据,但是当我向实时数据中添加观察者时,应用崩溃引发此异常.

I am trying to implement the new android architecture components and have used live data in the fragment and view model but when I add an observer to the live data the app crashes throwing this exception.

Process: com.nrs.nsnik.architecturecomponents, PID: 3071

java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.nrs.nsnik.architecturecomponents/com.nrs.nsnik.architecturec
omponents.view.MainActivity}: java.lang.ClassCastException: android.arch.lifecycle.LiveData_LifecycleBoundObserver_LifecycleAdapter cannot be cast to android.arch.lifecycle.GeneratedAdapter
.
.
.
.
 Caused by: java.lang.ClassCastException: android.arch.lifecycle.LiveData_LifecycleBoundObserver_LifecycleAdapter cannot be cast to android.arch.lifecycle.GeneratedAdapter

列表片段:

public class ListFragment extends Fragment {

    @BindView(R.id.listFragmentRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.listFragmentAddItem)
    FloatingActionButton mFloatingActionButton;
    private Unbinder mUnbinder;
    private CompositeDisposable mCompositeDisposable;
    private ListViewModel mListViewModel;
    private List<NoteEntity> mNoteEntityList;
    private ListAdapter mListAdapter;
    private NoteDatabase mNoteDatabase;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_list, container, false);
        mUnbinder = ButterKnife.bind(this, v);
        mListViewModel = ViewModelProviders.of(this).get(ListViewModel.class);
        mNoteDatabase = ((MyApplication)getActivity().getApplication()).getNoteDatabaseInstance();
        initialize();
        listeners();
        return v;
    }

    private void initialize() {
        mCompositeDisposable = new CompositeDisposable();
        mNoteEntityList = new ArrayList<>();
        mListAdapter = new ListAdapter(getActivity(), mNoteEntityList);
        mListViewModel.getNoteList().observe(this, noteEntityList -> {
            mListAdapter.swapList(noteEntityList);
            mListAdapter.notifyDataSetChanged();
        });
    }

    private void cleanUp() {
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
        if (mCompositeDisposable != null) {
            mCompositeDisposable.dispose();
        }
    }

    private void listeners() {
        RxView.clicks(mFloatingActionButton).subscribe(o -> {
        AlertDialog.Builder newNoteDialog = new AlertDialog.Builder(getActivity());
        View v = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_add_note_dialog, null);
        newNoteDialog.setView(v);
        EditText editText = v.findViewById(R.id.addNoteEditText);
        newNoteDialog.setNegativeButton(getActivity().getResources().getString(R.string.cancel), (dialogInterface, i) -> {
        }).setPositiveButton(getActivity().getResources().getString(R.string.add), (dialogInterface, i) -> {
            if (isValid(editText)) {
                NoteEntity entity = new NoteEntity();
                entity.setNote(editText.getText().toString());
                entity.setDate(getCurrentDate());
                mNoteDatabase.getNoteDao().insertNote(entity);
            }
        });
        newNoteDialog.create().show();
        });
    }

    private Date getCurrentDate() {
        Date date = new Date(Calendar.getInstance().getTimeInMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
        simpleDateFormat.format(date);
        return date;
    }

    private boolean isValid(EditText editText) {
        return !(editText.getText().toString().length() <= 0 || editText.getText().toString().isEmpty());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        cleanUp();
        if (BuildConfig.DEBUG) {
            RefWatcher refWatcher = MyApplication.getRefWatcher(getActivity());
            refWatcher.watch(this);
        }
    }
}

ViewModel:

ViewModel :

public class ListViewModel extends AndroidViewModel {

    private LiveData<List<NoteEntity>> mNoteList;
    private final NoteDatabase mNoteDatabase;

    ListViewModel(Application application) {
        super(application);
        mNoteDatabase = ((MyApplication)application).getNoteDatabaseInstance();
        mNoteList = mNoteDatabase.getNoteDao().getNoteList();
    }

    public LiveData<List<NoteEntity>> getNoteList() {
        return mNoteList;
    } 
}

NoteDatabase:

NoteDatabase :

@Database(entities = {NoteEntity.class}, version = 1)
public abstract class NoteDatabase extends RoomDatabase {
    public abstract NoteDao getNoteDao();
}

如果在实时数据上添加正面,则应用程序将崩溃.

App crashes if a add the obverse on the live data.

我正在使用"Room.databaseBuilder(....)"函数在应用程序类中构建数据库的单个实例,并在各处使用它,并且我的NoteEntity类具有三个字段,一个是id,它是自动生成的主键-生成.

I am building a single instance of the database in my application class using "Room.databaseBuilder(....)" function and using it everywhere and my NoteEntity class has three fields one is id which is a primary key that auto-generates.

推荐答案

我有类似的错误,在我的情况下是由gradle.build文件中的这种依赖性引起的:

I had similar error, in my case was caused by this dependency in gradle.build file:

implementation "android.arch.lifecycle:common-java8:1.0.0-beta2"

这篇关于Android Live数据观察器异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆