gpt4 book ai didi

java - 使用 livedata 的 Recyclerview 在数据更改后不会更新。仅在我旋转屏幕后

转载 作者:行者123 更新时间:2023-12-01 18:02:36 25 4
gpt4 key购买 nike

我有一个天气应用程序,允许用户保存位置(存储在本地房间数据库中)并显示所述位置的天气。当用户将城市添加到数据库时,我执行天气 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());
}

}

现在我在用户界面中有一个按钮可以一次更新所有城市(最终我希望它是一个简单的向下滚动来更新或类似的东西)。问题是,当我单击更新所有城市时,工作已执行,但 recyclerview 未更新(因为新数据未传递给它),但如果我更改配置(如旋转屏幕),新数据将显示。

这是我的主要类(class):

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);
}

Here is what the app looks like

最佳答案

我认为真正的问题是因为您正在调用 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

关于java - 使用 livedata 的 Recyclerview 在数据更改后不会更新。仅在我旋转屏幕后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60603670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com