Android Live data observer exception

。_饼干妹妹 提交于 2019-12-23 18:52:49

问题


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

List Fragment :

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 :

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 :

@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.

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.


回答1:


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"



回答2:


The FirebaseUI has not yet updated android.arch.lifecycle to 1.0.0-beta2.

Use 1.0.0-beta1 instead of 1.0.0-beta2.
Wait until they update the lifecycle library.



来源:https://stackoverflow.com/questions/46649349/android-live-data-observer-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!