【发布时间】:2021-03-22 13:22:22
【问题描述】:
我尝试使用 this 实现 ViewModel。但是从不调用观察。
基本上这个应用程序在 SAMPLE_URL 上发出网络请求,将 JSON 转换为 List 并通过 bookView 显示列表。该应用程序在没有 ViewModel 的情况下运行良好。使用 ViewModel 时,应用程序会运行,但从不调用观察,也不会显示任何数据。
我在这里做错了什么?
BookActivity 类:
public BookAdapter bookAdapter;
ListView bookView;
public final static String SAMPLE_URL = "https://www.googleapis.com/books/v1/volumes?q=search+terms";
public ArrayList<Book> books = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitymain);
bookView = findViewById(R.id.list);
bookAdapter = new BookAdapter(BookActivity.this,books);
BookViewModel bookViewModel = new ViewModelProvider(this).get(BookViewModel.class);
bookViewModel.getBooks().observe(this, books -> {
Log.d("INSIDE", "observe");
bookAdapter = new BookAdapter(this,books);
bookView.setAdapter(bookAdapter);
bookAdapter.notifyDataSetChanged();
});
}
BookViewModel 类:
public class BookViewModel extends ViewModel {
public MutableLiveData<List<Book>> books;
public LiveData<List<Book>> getBooks(){
if (books == null) {
books = new MutableLiveData<>();
loadBooks();
}
return books;
}
private void loadBooks() {
thread.start();
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
URL url = QueryUtility.createURL(BookActivity.SAMPLE_URL);
try{
assert url != null;
String JSONResponse = QueryUtility.ReadFromStream(QueryUtility.MakeHTTPRequest(url));
books = new MutableLiveData<>(QueryUtility.extractBooksFromJSON(JSONResponse));
}
catch (IOException | JSONException ioException){
ioException.printStackTrace();
}
}
});
}
【问题讨论】: