gpt4 book ai didi

java - ANDROID:MVVM + Retrofit:如何以及在哪里从 JSON 对象数组检索 JSON 对象列表?

转载 作者:行者123 更新时间:2023-12-02 04:32:54 26 4
gpt4 key购买 nike

我已经设置了通话的所有内容,但我得到的列表大小为 0。经过一番研究,我意识到我正在尝试检索 JSON 对象,同时我的 response.body 的根是一个 JSON 数组。我检查过网络,似乎我应该向我的“任务”(这是我的模型)添加一个包装器,用列表进行调用。但我不明白到底该怎么做。我应该在哪里获取 JSON 数组,以及在哪里以及如何准确地将 JSON 对象数组根解析为 JSON 对象列表,以便我可以继续在回收器 View 中进行绑定(bind)。

型号:

public class Task {
@SerializedName("taskId")
@Expose
private int taskId;

private int requestId;

private int currentEventId;

private int technicianId;

private int supervisorId;

private String status;

@SerializedName("category")
@Expose
@Nullable
private String itemCategory;


@SerializedName("brand")
@Expose
@Nullable
private String itemBrand;


@SerializedName("model")
@Expose
@Nullable
private String itemModel;


@SerializedName("series")
@Expose
@Nullable
private String itemSeria;

@SerializedName("series")
@Expose
@Nullable
private String address;

private String requestIndicator;
private String requestCode;
private String requestName;
private String requestCompanyLogo;

@SerializedName("assignDate")
@Expose
private String assignDate;

@SerializedName("assignDate")
@Expose
private String assignTime;

private List<Task> tasks = null;


public int getTaskId() {
return taskId;
}

public void setTaskId(int taskId) {
this.taskId = taskId;
}

public int getRequestId() {
return requestId;
}

public void setRequestId(int requestId) {
this.requestId = requestId;
}

public int getCurrentEventId() {
return currentEventId;
}

public void setCurrentEventId(int currentEventId) {
this.currentEventId = currentEventId;
}

public int getTechnicianId() {
return technicianId;
}

public void setTechnicianId(int technicianId) {
this.technicianId = technicianId;
}

public int getSupervisorId() {
return supervisorId;
}

public void setSupervisorId(int supervisorId) {
this.supervisorId = supervisorId;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}

public String getAssignDate() {
return assignDate;
}

public void setAssignDate(String assignDate) {
this.assignDate = assignDate;
}

public String getRequestName() {
return requestName;
}

public void setRequestName(String requestName) {
this.requestName = requestName;
}

public String getItemCategory() {
return itemCategory;
}

public void setItemCategory(String itemCategory) {
this.itemCategory = itemCategory;
}

public String getItemBrand() {
return itemBrand;
}

public void setItemBrand(String itemBrand) {
this.itemBrand = itemBrand;
}

public String getItemModel() {
return itemModel;
}

public void setItemModel(String itemModel) {
this.itemModel = itemModel;
}

public String getItemSeria() {
return itemSeria;
}

public void setItemSeria(String itemSeria) {
this.itemSeria = itemSeria;
}

public String getRequestIndicator() {
return requestIndicator;
}

public void setRequestIndicator(String requestIndicator) {
this.requestIndicator = requestIndicator;
}

public String getRequestCode() {
return requestCode;
}

public void setRequestCode(String requestCode) {
this.requestCode = requestCode;
}

public String getRequestCompanyLogo() {
return requestCompanyLogo;
}

public void setRequestCompanyLogo(String requestCompanyLogo) {
this.requestCompanyLogo = requestCompanyLogo;
}

public String getAssignTime() {
return assignTime;
}

public void setAssignTime(String assignTime) {
this.assignTime = assignTime;
}

public List<Task> getTasks() {
return tasks;
}

public void setTasks(List<Task> tasks) {
this.tasks = tasks;
}

}

网络服务:

public interface TaskWebService {
@GET("tasks/new")
Call<List<Task>> getTasks(@Query("count") int count, @Query("pageNumber") int pageNumber, @Query("taskStatus") String taskStatus, @Header("token") String token);

}

改造网络服务:

public class RetrofitNetworkService {

private static final String BASE_URL = "bla bla bla";


private static Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();

public static <S> S createService(Class<S> serviceClass) {
return retrofit.create(serviceClass);
}

}

任务存储库:

public class TaskRepo {

private static TaskRepo taskRepo;
private static TaskWebService taskWebService;

private TaskRepo() {
taskWebService =
RetrofitNetworkService.createService(TaskWebService.class);
}

public static TaskRepo getInstance() {
if (taskRepo == null) {
taskRepo = new TaskRepo();
}
return taskRepo;
}

public MutableLiveData<List<Task>> getTasks(int count, int pageNumber, String taskStatus, String token) {

final MutableLiveData<List<Task>> allTasks = new MutableLiveData<>();

taskWebService.getTasks(count, pageNumber, taskStatus, token).enqueue(new Callback<List<Task>>() {
@Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
if (response.isSuccessful()) {
allTasks.setValue(response.body());
}
}

@Override
public void onFailure(Call<List<Task>> call, Throwable t) {
allTasks.setValue(null);
t.printStackTrace();
}
});
return allTasks;
}

}

View 模型:

公共(public)类 ViewModelTask​​ 扩展 ViewModel {

private MutableLiveData<List<Task>> allTasks = new MutableLiveData<>();
private TaskRepo taskRepo;

public void initialize() {
if (allTasks != null) {
return;
}
taskRepo = TaskRepo.getInstance();
allTasks = taskRepo.getTasks(15, 0, "", ""code);
}

public LiveData<List<Task>> getAllTasks() {
return allTasks;
}

}

查看:

公共(public)类 FragmentTabAll 扩展 Fragment {

private RecyclerView taskRecyclerView;
private int adapterType;
private List<Task> taskList = new ArrayList<>();
private ViewModelTask viewModelTask;
private TaskAdapter taskAdapter;


public FragmentTabAll(int adapterType) {
this.adapterType = adapterType;
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab_all, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
taskRecyclerView = view.findViewById(R.id.task_cardview);
taskAdapter = new TaskAdapter(getActivity());
checkAdapterType();
}

private void checkAdapterType() {
if (adapterType == Utils.TASK_ADAPTER) {
taskRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
viewModelTask = ViewModelProviders.of(this).get(ViewModelTask.class);
viewModelTask.initialize();
taskRecyclerView.setAdapter(taskAdapter);

viewModelTask.getAllTasks().observe(getActivity(), new Observer<List<Task>>() {
@Override
public void onChanged(List<Task> tasks) {
taskList.addAll(tasks);
taskRecyclerView.setAdapter(taskAdapter);
taskAdapter.setTaskList(taskList);
}
});
taskRecyclerView.setAdapter(taskAdapter);

} else if (adapterType == Utils.REQUEST_ADAPTER) {
taskRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
taskRecyclerView.setAdapter(new RequestAdapter(getActivity()));
}
}

}

我期望获得一个充满任务的回收器 View (当我手动填充列表时,项目的数据绑定(bind)起作用),但是当我尝试实现调用时,我得到一个空列表。

最佳答案

我无法调试你的代码,但看到它我认为问题出在这里:

 public MutableLiveData<List<Task>> getTasks(int count, int pageNumber, String taskStatus, String token) {

final MutableLiveData<List<Task>> allTasks = new MutableLiveData<>();

taskWebService.getTasks(count, pageNumber, taskStatus, token).enqueue(new Callback<List<Task>>() {
@Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
if (response.isSuccessful()) {
allTasks.setValue(response.body());
}
}

@Override
public void onFailure(Call<List<Task>> call, Throwable t) {
allTasks.setValue(null);
t.printStackTrace();
}
});
return allTasks;
}

getTasks 是一个异步调用,因为您从界面返回 Call (如果您想要同步行为,您可能需要 reutnr 列表或其他),因此 allTask​​s LiveData 不会等待响应,而只是返回空 LiveData。

我建议您使用回调,只需将返回值更改为 void,然后在参数上传递回调,例如:

public void getTasks(int count, int pageNumber, String taskStatus, String token, OnCompleteCallback onComplete) {


taskWebService.getTasks(count, pageNumber, taskStatus, token).enqueue(new Callback<List<Task>>() {
@Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
if (response.isSuccessful()) {
onComplete.done(response.body())
}
}

@Override
public void onFailure(Call<List<Task>> call, Throwable t) {
onComplete.done(null)
t.printStackTrace();
}
});
}

现在,您应该做的是更改 View 模型以发布数据,以便您的 Activity/fragment 可以接收您的更改

allTasks = taskRepo.getTasks(15, 0, "", ""code, new OnCompleteCallback<>{
@Override
void done(List<Tasks> mListTasks){
if (mListTasks != null){
allTasks.postValue(mListTaks)
}
}
});

此时,您的 Activity/fragment 必须观察所有任务,然后您就可以执行您需要的操作。希望这对您有帮助

关于java - ANDROID:MVVM + Retrofit:如何以及在哪里从 JSON 对象数组检索 JSON 对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56569332/

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