Я пытаюсь использовать mvvm в первый раз и закончил с ошибкой ссылки на нулевой объект.
Я ссылался на эту ссылку для того же: https://medium.com/@kenkyee / retrofit2-doesnt- handle-empty-content-answers-bef2b33ee8ea
Я получаю ответ от api и сохраняю его в базе данных комнаты, а затем извлекаю то же самое с использованием модели представления и наблюдателя из базы данных комнаты для отображения в списке.
Вот мой код:
Репозиторий:
public class WebServiceRepository {
String responseString = "";
Application application;
public WebServiceRepository(Application application){
this.application = application;
}
private static OkHttpClient providesOkHttpClientBuilder(){
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
return httpClient.readTimeout(1200, TimeUnit.SECONDS)
.connectTimeout(1200, TimeUnit.SECONDS).build();
}
List<Photos> webserviceResponseList = new ArrayList<>();
public LiveData<List<Photos>> providesWebService() {
final MutableLiveData<List<Photos>> data = new MutableLiveData<>();
try {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(APIUrl.BASE_URL)
/* .addConverterFactory(new NullOnEmptyConverterFactory())
.addConverterFactory(ScalarsConverterFactory.create())*/
.addConverterFactory(GsonConverterFactory.create())
.client(providesOkHttpClientBuilder())
.build();
//Defining retrofit api service
APIService service = retrofit.create(APIService.class);
service.makeRequest().enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
responseString = response.toString();
Log.d("Repository","Response::::"+response.body());
webserviceResponseList = parseJson(response.body());
PhotosRoomDBRepository photosRoomDBRepository =
new PhotosRoomDBRepository(application);
photosRoomDBRepository.insertPhotos(webserviceResponseList);
data.setValue(webserviceResponseList);
}
@Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("Repository","Failed:::");
}
});
/*
service.makeRequest().enqueue(new Callback<String>() {
@Override public void onResponse(
Call<String> call, Response<String> response
) {
Log.d("Repository","Response::::"+response.body());
webserviceResponseList = parseJson(response.body());
PhotosRoomDBRepository photosRoomDBRepository =
new PhotosRoomDBRepository(application);
photosRoomDBRepository.insertPosts(webserviceResponseList);
data.setValue(webserviceResponseList);
}
@Override public void onFailure(Call<String> call, Throwable t) {
Log.d("Repository","Failed:::");
}
});*/
}catch (Exception e){
e.printStackTrace();
}
return data;
}
private List<Photos> parseJson(String response) {
List<Photos> apiResults = new ArrayList<>();
JSONObject jsonObject;
JSONArray jsonArray;
try {
jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Photos photos = new Photos();
photos.setId(Integer.parseInt(object.getString("id")));
photos.setAlbumId(Integer.parseInt(object.getString("albumId")));
photos.setTitle(object.getString("title"));
photos.setUrl(object.getString("url"));
photos.setThumbnailUrl(object.getString("thumbnailUrl"));
apiResults.add(photos);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i(getClass().getSimpleName(), String.valueOf(apiResults.size()));
return apiResults;
}
}
Просмотр модели
public class MainViewModel extends AndroidViewModel {
// TODO: Implement the ViewModel
private PhotosRoomDBRepository photosRoomDBRepository;
private LiveData<List<Photos>> mPhotos;
WebServiceRepository webServiceRepository ;
private LiveData<List<Photos>> photoObservable;
public MainViewModel(Application application){
super(application);
photosRoomDBRepository = new PhotosRoomDBRepository(application);
webServiceRepository = new WebServiceRepository(application);
photoObservable = webServiceRepository.providesWebService();
//postRoomDBRepository.insertPosts(retroObservable.getValue());
photoObservable = photosRoomDBRepository.getAllPhotos();
}
public LiveData<List<Photos>> getAllPhotos() {
return mPhotos;
}
}
Фрагмент:
public class MainFragment extends Fragment {
private MainViewModel mViewModel;
ArrayList<Photos> photosArrayList = new ArrayList<>();
private RecyclerView recyclerView;
private PhotosAdapter photosAdapter;
ProgressDialog progressDialog;
public static MainFragment newInstance() {
return new MainFragment();
}
@Nullable
@Override
public View onCreateView(
@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState
) {
View view = inflater.inflate(R.layout.main_fragment, container, false);
setUpUI(view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(getActivity()).get(MainViewModel.class);
// TODO: Use the ViewModel
setUpRecyclerView();
getDataFromLocalDatabase();
}
public void setUpUI(View view) {
recyclerView = view.findViewById(R.id.recycler_view_photos);
}
public void setUpRecyclerView() {
photosAdapter = new PhotosAdapter(photosArrayList, getActivity());
RecyclerView.LayoutManager mLayoutManager =
new GridLayoutManager(getActivity(), 3);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new GridSpacingItemDecoration(3, 10,
true, 0
));
recyclerView.setAdapter(photosAdapter);
}
public void getDataFromLocalDatabase(){
progressDialog = ProgressDialog.show(getActivity(), "Loading...",
"Please wait...", true);
mViewModel.getAllPhotos().observe(getActivity(),
new Observer<List<Photos>>() {
@Override
public void onChanged(@Nullable List<Photos> photos) {
photosAdapter.updateList(photos);
if(progressDialog!=null && progressDialog.isShowing()){
progressDialog.dismiss();
}
}
});
}
}
Я получаю сообщение об ошибке:
mViewModel.getAllPhotos().observe(getActivity(),
new Observer<List<Photos>>() {
@Override
public void onChanged(@Nullable List<Photos> photos) {
photosAdapter.updateList(photos);
if(progressDialog!=null && progressDialog.isShowing()){
progressDialog.dismiss();
}
}
});
Помогите, пожалуйста, с тем же спасибо ..