我正在尝试使用android ViewModel和LiveData,但是当我想创建观察时出现错误。第一个参数给我一个错误:错误的第一个参数类型,它是期望Lifecycleowner。如果我尝试构建它:不兼容的类型:FragStat无法转换为LifecycleOwner 我正在使用构建工具27.0.1和支持库。
这是我的片段:
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.example.konem.pubgstat.Adapters.StatAdapter;
import com.example.konem.pubgstat.LocalStatViewModel;
import com.example.konem.pubgstat.Models.LocalStat;
import com.example.konem.pubgstat.R;
import com.example.konem.pubgstat.Utils.LocalData.AppDatabase;
import com.example.konem.pubgstat.Utils.UserManager;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import java.util.List;
import static android.content.ContentValues.TAG;
@EFragment(R.layout.fragment_frag_stat)
public class FragStat extends Fragment {
private List<LocalStat> localStats;
private StatAdapter statAdapter;
private AppDatabase appDatabase;
private UserManager userManager;
@ViewById
RecyclerView rvStats;
@AfterViews
void init() {
appDatabase = AppDatabase.getAppDatabase(getActivity());
userManager = new UserManager(getActivity());
LocalStatViewModel mViewModel =
ViewModelProviders.of(this).get(LocalStatViewModel.class);
statAdapter = new StatAdapter(localStats);
rvStats.setLayoutManager(new LinearLayoutManager(getActivity()));
rvStats.setAdapter(statAdapter);
subscribetostats(mViewModel);
}
private void subscribetostats(LocalStatViewModel localStatViewModel) {
localStatViewModel.getList().observe(this, new Observer<List<LocalStat>>() {
@Override
public void onChanged(@Nullable List<LocalStat> localStats) {
}
});
}
}
答案 0 :(得分:0)
设置从DOA界面获取记录的返回类型为
LiveData<List<LocatStat>> getAllStats();
然后获取片段中的实时数据
LiveData<List<LocalStat> localStats;
最后在片段
中设置Livedata观察者localStats.getList().observe(this, new Observer<List<LocalStat>>() {
@Override
public void onChanged(@Nullable List<LocalStat> localStats) {
// Update UI
}
});
答案 1 :(得分:0)
所以经过几天尝试后我发现了问题。你必须在每个片段或活动中包含这几行,我认为是由appcombat实现但不是......
private LifecycleRegistry mLifecycleRegistry;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
}
@Override
public void onStart() {
super.onStart();
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}