gpt4 book ai didi

android - retrofit 2 : Object is not being formed correctly after sending to server

转载 作者:行者123 更新时间:2023-11-29 01:13:11 24 4
gpt4 key购买 nike

这是我的界面:

public interface DistributionServerAPI {
@Headers("Content-type: application/json")
@POST("device/add")
Call<DeviceModel> createDevice(@Body ArrayList<DeviceModel> deviceArray);
}

在我的 Device.java 文件中:

public class Device extends Fragment {
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (numberOfDevices > 0) {
for (int i = 0; i < numberOfDevices; i++) {
ViewGroup viewGroup = (ViewGroup)rootView.findViewById(i);
for (int index = 1; i < viewGroup.getChildCount(); index++) {
DeviceModel device = new DeviceModel();
switch (index) {
case 1:
device.setName(deviceName);
break;
case 2:
device.setColor(deviceColor);
break;
}
}
deviceModelArrayList.add(device);
}

Call<DeviceModel> deviceModel = api.createDevice(deviceModelArrayList);

deviceModel.enqueue(new Callback<DeviceModel>() {
@Override
public void onResponse(Call<DeviceModel> call, Response<DeviceModel> response) {
Log.d("POSTING DEVICE", "DEVICE SAVE WAS SUCCESS");
}

@Override
public void onFailure(Call<DeviceModel> call, Throwable t) {
Log.d("POSTING DEVICE", "DEVICE SAVE WAS FAILURE");
}
});
}
}
});
}

在上面的 Device.java 中,我创建了我的 ArrayList(deviceModelArrayList 变量),它有设备对象(DeviceModel ) 包含 2 个属性名称和颜色。

正在将 ArrayList 发送到服务器,但由于某种原因,对象未正确形成。在 for 循环的 switch 语句中,我设置了设备的 namecolor,并将其添加到 ArrayList

我有 4 个设备被添加到 ArrayList 但是当我在服务器端打印对象时我只有 2 个设备对象并且 color 属性不是甚至存在于任何这些物体中。

看起来像这样:

[{"name": "device1"}, {"name": "device2"}]

没有颜色属性,只有 2 个设备而不是 4 个。对我做错了什么有什么想法吗?在for循环里面用switch可以吗。比如 break 语句是只跳出 switch 还是跳出内部 for 循环?

最佳答案

第一个,如果你想获得这样的 View ,你应该使用标签而不是 id。第二个你可以从你的代码中看到

for (int index = 1; i < viewGroup.getChildCount(); index++) {
DeviceModel device = new DeviceModel();
switch (index) {
case 1:
device.setName(deviceName);
break;
case 2:
device.setColor(deviceColor);
break;
}
}

使用此逻辑,您的设备模型将永远不会同时具有名称和颜色,因为您正在循环中创建一个新对象,您还可以在循环中设置属性。

如果你想为每个 ViewGroup 保留一个 DeviceModel,你的代码应该是这样的

         for (int i = 0; i < numberOfDevices; i++) {
ViewGroup viewGroup = (ViewGroup)rootView.findViewById(i);
DeviceModel device = new DeviceModel();
for (int index = 1; i < viewGroup.getChildCount(); index++) {
switch (index) {
case 1:
device.setName(deviceName);
break;
case 2:
device.setColor(deviceColor);
break;
}
}
deviceModelArrayList.add(device);
}

这样,您将为每个 ViewGroup 拥有一个 DeviceModel,而不是为每个 ViewGroupChild 拥有一个

关于android - retrofit 2 : Object is not being formed correctly after sending to server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41605211/

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