我有一个气象应用程序,允许用户保存位置(本地存储在房间DB中)并显示所述位置的天气。当用户将城市添加到数据库时,我将执行天气API调用,然后使用所需的信息将城市添加到数据库中。
public class InsertSingleCityWorker extends Worker {
private MyCitiesDatabase citiesDatabase;
private String nickname;
private int zip;
private static final String TAG = "APICallsWorker";
public InsertSingleCityWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
citiesDatabase = MyCitiesDatabase.getInstance(getApplicationContext());
Log.d(TAG, "APICallsWorker: WORK CREATED");
}
@NonNull
@Override
public Result doWork() {
nickname = getInputData().getString("nickname");
zip = getInputData().getInt("zip", -1);
performAPICalls();
return Result.success();
}
private void performAPICalls() {
WeatherApi weatherApi = RetrofitService.createService(WeatherApi.class);
weatherApi.getWeatherWithZip(zip, Constants.API_KEY).enqueue(new Callback<WeatherResponse>() {
@Override
public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
if(response.isSuccessful()){
if(response.body() != null){
handleAPIResult(response.body());
}
} else{
Toast.makeText(getApplicationContext(), "Please Enter a valid zip", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<WeatherResponse> call, Throwable t) {
handleError(t);
}
});
}
private void handleAPIResult(WeatherResponse weatherResponse) {
Log.d(TAG, "handleAPIResult: HERE");
Completable.fromAction(() -> {
String timestamp = StringManipulation.getCurrentTimestamp();
int temperature = Integer.valueOf(Conversions.kelvinToFahrenheit(weatherResponse.getMain().getTemp()));
String locationName = weatherResponse.getName();
int windSpeed = Math.round(weatherResponse.getWind().getSpeed());
int humidity = Math.round(weatherResponse.getMain().getHumidity());
MyCity city = new MyCity(nickname, zip, timestamp, temperature, locationName, windSpeed, humidity);
citiesDatabase.myCitiesDao().insert(city);
}).observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe();
}
private void handleError(Throwable t) {
Log.d(TAG, "handleError: ERROR: " + t.getMessage());
}
}
现在我在UI中有一个按钮可以立即更新所有城市(最终我希望它是一个简单的向下滚动以进行更新或类似的操作)。问题是,当我单击“更新所有城市”时,将执行工作,但recyclerview不会更新(因为未将新数据传递给它),但是如果我更改配置(例如旋转屏幕),则会显示新数据。
这是我的主要课程:
public class MainActivity extends AppCompatActivity implements AddCityDialog.AddCityDialogListener {
private static final String TAG = "MainActivity";
//Widgets
private Button mAddNewCity;
private RecyclerView mRecyclerView;
private WeatherRecyclerAdapter mRecyclerAdapter;
private ViewAddDeleteCitiesViewModel mViewDeleteViewModel;
private ViewAddDeleteCitiesViewModelFactory mViewDeleteMyCitiesViewModelFactory;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initWidgets();
initViewModel();
initRecyclerView();
setupListeners();
}
public void initWidgets() {
mAddNewCity = findViewById(R.id.btn_add_new_city);
}
public void initViewModel() {
mViewDeleteMyCitiesViewModelFactory = new ViewAddDeleteCitiesViewModelFactory(this.getApplication());
mViewDeleteViewModel = new ViewModelProvider(this, mViewDeleteMyCitiesViewModelFactory).get(ViewAddDeleteCitiesViewModel.class);
mViewDeleteViewModel.observeAllCities().observe(this, cities -> mRecyclerAdapter.submitList(cities));
}
public void setupListeners() {
mAddNewCity.setOnClickListener(v -> addCityDialog());
mRecyclerAdapter.setOnItemClickListener(myCity -> Toast.makeText(MainActivity.this, "Item Clicked: ", Toast.LENGTH_SHORT).show());
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
mViewDeleteViewModel.delete(mRecyclerAdapter.getCityAt(viewHolder.getAdapterPosition()));
Log.d(TAG, "onSwiped: Deleted");
}
}).attachToRecyclerView(mRecyclerView);
}
public void addCityDialog() {
AddCityDialog addCityDialog = new AddCityDialog();
addCityDialog.show(getSupportFragmentManager(), "Add City Dialog");
}
public void initRecyclerView() {
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerAdapter = new WeatherRecyclerAdapter();
mRecyclerView.setAdapter(mRecyclerAdapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
Log.d(TAG, "initRecyclerView: Recycler View Initialized");
}
/**
* Uses information (@param nickname @param zip) from Dialog to add a new city to the room db
* by passing the input to the one time worker class.
* @param nickname
* @param zip
*/
@Override
public void addCity(String nickname, String zip) {
insertSingleCity(nickname, Integer.valueOf(zip));
Log.d(TAG, "addCity: CITY ADDED MAIN ACTIVITY");
updateAllCities(mViewDeleteViewModel.getAllCities());
}
public void insertSingleCity(String nickname, int zip) {
OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(InsertSingleCityWorker.class)
.setInputData(DataManipulation.createInputData(nickname, zip))
.build();
WorkManager.getInstance(this).enqueue(oneTimeWorkRequest);
}
public void updateCities(View v){
updateAllCities(mViewDeleteViewModel.getAllCities());
}
//Stars work to get API when a city is added
private void updateAllCities(List<MyCity> cities) {
Log.d(TAG, "startWork: here");
for (MyCity city : cities) {
OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(UpdateAllCitiesWorker.class)
.setInputData(DataManipulation.createInputData(city.getId(), city.getNickname(), city.getZipCode()))
.build();
WorkManager.getInstance(this).enqueue(oneTimeWorkRequest);
Log.d(TAG, "startWork: WORK ENQUEUED");
}
}
}
更新所有城市工作人员:
public UpdateAllCitiesWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
citiesDatabase = MyCitiesDatabase.getInstance(getApplicationContext());
Log.d(TAG, "APICallsWorker: WORK CREATED");
}
@NonNull
@Override
public Result doWork() {
id = getInputData().getLong("id", -1);
nickname = getInputData().getString("nickname");
zip = getInputData().getInt("zip", -1);
performAPICalls();
return Result.success();
}
private void performAPICalls() {
WeatherApi weatherApi = RetrofitService.createService(WeatherApi.class);
weatherApi.getWeatherWithZip(zip, Constants.API_KEY).enqueue(new Callback<WeatherResponse>() {
@Override
public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
handleAPIResult(response.body());
}
}
}
@Override
public void onFailure(Call<WeatherResponse> call, Throwable t) {
handleError(t);
}
});
}
private void handleAPIResult(WeatherResponse weatherResponse) {
Log.d(TAG, "handleAPIResult: HERE");
Completable.fromAction(() -> {
String timestamp = StringManipulation.getCurrentTimestamp();
int temperature = Integer.valueOf(Conversions.kelvinToFahrenheit(weatherResponse.getMain().getTemp()));
String locationName = weatherResponse.getName();
int windSpeed = Math.round(weatherResponse.getWind().getSpeed());
int humidity = Math.round(weatherResponse.getMain().getHumidity());
MyCity city = new MyCity(nickname, zip, timestamp, temperature, locationName, windSpeed, humidity);
city.setId(id);
citiesDatabase.myCitiesDao().update(city);
Log.d(TAG, "run: city added");
}).observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe();
}
private void handleError(Throwable t) {
Log.d(TAG, "handleError: here");
}
}
还有道:
@Dao
public interface MyCitiesDao {
@Insert
void insert(MyCity myCity);
@Query("SELECT * FROM cities ORDER BY id ASC")
LiveData<List<MyCity>> observeAllCities();
@Query("SELECT * FROM cities ORDER BY id ASC")
List<MyCity> getAllCities();
@Delete
void delete(MyCity... city);
@Update
void update(MyCity... city);
}
答案 0 :(得分:0)
我认为真正的问题是因为您致电submitList
是因为根据docs
当您调用submitList时,它将提交一个新列表以进行差异显示。
这就是为什么每当您在上一个(已提交的列表)上调用SubmitList时,它都不会计算Diff且不会通知适配器数据集中的更改。
一种解决方案可能是使用以下方法(我认为不是很好),但应该可以。
submitList(null);
submitList(cities);
另一种解决方案是覆盖适配器类中的SubmitList
@Override
public void submitList(final List<MyCity> list) {
super.submitList(list != null ? new ArrayList<>(list) : null);
}
第三个解决方案是创建如下列表的副本
submitList(new ArrayList(cities))
请查看此stackoverflow问题以获取更多信息source