我正在使用RetroFit 2.1.0将设备对象发布到我的MongoDB数据库:
public class Device extends Fragment {
EditText deviceName;
EditText numDevices;
Button submitButton;
private API api;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.master_view, container, false);
deviceName = (EditText) rootView.findViewById(R.id.device_name);
numDevices = (EditText)
rootView.findViewById(R.num_devices);
submitButton = (Button) rootView.findViewById(R.id.submit_button);
Retrofit retroFit = new Retrofit.Builder()
.baseUrl(getString(R.string.base_url))
.addConverterFactory(GsonConverterFactory.create())
.build();
api = retroFit.create(API.class);
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveDevice();
}
});
return rootView;
}
public void saveDevice() {
//THIS LINE OF CODE IS NOT RUNNING NOT SURE WHY?
System.out.println("GOT INTO SAVE MASTER");
DeviceModel device = new DeviceModel();
device.setDeviceName(deviceName.getText().toString());
device.numOfDevices(Integer.parseInt(numDevices.getText().toString()));
Call<DeviceModel> deviceModel = api.createDevice(device);
deviceModel.enqueue(new Callback<DeviceModel>() {
@Override
public void onResponse(Call<DeviceModel> call, Response<DeviceModel> response) {
System.out.print("Success" + response.code());
}
@Override
public void onFailure(Call<DeviceModel> call, Throwable t) {
System.out.print(t.getLocalizedMessage());
}
});
}
}
这是我的API.java:
public interface API {
//Device endpoint
@POST("device/insert")
Call<DeviceModel> createDevice(@Body DeviceModel master);
}
我使用RetroFit 2.1.0将设备对象保存到http://localhost:3000
上运行的MongoDB实例。当我在邮递员上点击端点http://localhost:3000/device/insert
时,它会将设备JSON对象保存到数据库。
但是当我使用RetroFit通过应用程序执行此操作时,它似乎根本不起作用。我在saveDevice
方法中做错了吗?