Alice Alice - 6 months ago 22
Android Question

How to send information from a server to Android

I've got a server. How can I send information from the server to my Android app? This is one of my controller methods:

@RequestMapping("/city/{cityId}")
public ModelAndView showCity(@PathVariable("cityId") int cityId){
ModelAndView mav=new ModelAndView("city/cityDetails");
mav.addObject(this.whatsNewService.findCityById(cityId));
return mav;
}

Answer

I this case you can not pass a ModelAndView (Actually you can). But the best option is to use REST. You can make this method a REST api method. and pass a Jason object.

In general, web applications expose their service through an REST api to be used by a third part applications or to power their mobile applications

@RestController
public class CityController {

   @Autowire
   private WhatsNewService whatsNewService;

   @RequestMapping(method = RequestMethod.GET, value = "/city/{cityId}")
   public City showCity(@PathVariable("cityId") int cityId){

    return this.whatsNewService.findCityById(cityId);
   }

}

Or you can use the same @Controller class and

@Controller
public class CityController {

   @Autowire
   private WhatsNewService whatsNewService;

   @RequestMapping(method = RequestMethod.GET, value = "/city/{cityId}")
   public @ResponseBody City showCity(@PathVariable("cityId") int cityId){

    return this.whatsNewService.findCityById(cityId);
   }

}

In android client side you can use RETROFIT like library to map your josn object to application object.