• Android annotations REST


    使用前:

      1 public class BookmarksToClipboardActivity extends Activity {
      2   
      3   BookmarkAdapter adapter;
      4  
      5   ListView bookmarkList;
      6  
      7   EditText search;
      8  
      9   BookmarkApplication application;
     10  
     11   Animation fadeIn;
     12  
     13   ClipboardManager clipboardManager;
     14  
     15   @Override
     16   protected void onCreate(Bundle savedInstanceState) {
     17     super.onCreate(savedInstanceState);
     18  
     19     requestWindowFeature(Window.FEATURE_NO_TITLE);
     20     getWindow().setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN);
     21  
     22     setContentView(R.layout.bookmarks);
     23  
     24     bookmarkList = (ListView) findViewById(R.id.bookmarkList);
     25     search = (EditText) findViewById(R.id.search);
     26     application = (BookmarkApplication) getApplication();
     27     fadeIn = AnimationUtils.loadAnimation(this, anim.fade_in);
     28     clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
     29  
     30     View updateBookmarksButton1 = findViewById(R.id.updateBookmarksButton1);
     31     updateBookmarksButton1.setOnClickListener(new OnClickListener() {
     32  
     33       @Override
     34       public void onClick(View v) {
     35         updateBookmarksClicked();
     36       }
     37     });
     38  
     39     View updateBookmarksButton2 = findViewById(R.id.updateBookmarksButton2);
     40     updateBookmarksButton2.setOnClickListener(new OnClickListener() {
     41  
     42       @Override
     43       public void onClick(View v) {
     44         updateBookmarksClicked();
     45       }
     46     });
     47  
     48     bookmarkList.setOnItemClickListener(new OnItemClickListener() {
     49  
     50       @Override
     51       public void onItemClick(AdapterView<?> p, View v, int pos, long id) {
     52         Bookmark selectedBookmark = (Bookmark) p.getAdapter().getItem(pos);
     53         bookmarkListItemClicked(selectedBookmark);
     54       }
     55     });
     56  
     57     initBookmarkList();
     58   }
     59  
     60   void initBookmarkList() {
     61     adapter = new BookmarkAdapter(this);
     62     bookmarkList.setAdapter(adapter);
     63   }
     64  
     65   void updateBookmarksClicked() {
     66     UpdateBookmarksTask task = new UpdateBookmarksTask();
     67  
     68     task.execute(search.getText().toString(), application.getUserId());
     69   }
     70   
     71   private static final String BOOKMARK_URL = //
     72   "http://www.bookmarks.com/bookmarks/{userId}?search={search}";
     73   
     74   
     75   class UpdateBookmarksTask extends AsyncTask<String, Void, Bookmarks> {
     76  
     77     @Override
     78     protected Bookmarks doInBackground(String... params) {
     79       String searchString = params[0];
     80       String userId = params[1];
     81  
     82       RestTemplate client = new RestTemplate();
     83       HashMap<String, Object> args = new HashMap<String, Object>();
     84       args.put("search", searchString);
     85       args.put("userId", userId);
     86       HttpHeaders httpHeaders = new HttpHeaders();
     87       HttpEntity<Bookmarks> request = new HttpEntity<Bookmarks>(httpHeaders);
     88       ResponseEntity<Bookmarks> response = client.exchange( //
     89           BOOKMARK_URL, HttpMethod.GET, request, Bookmarks.class, args);
     90       Bookmarks bookmarks = response.getBody();
     91  
     92       return bookmarks;
     93     }
     94  
     95     @Override
     96     protected void onPostExecute(Bookmarks result) {
     97       adapter.updateBookmarks(result);
     98       bookmarkList.startAnimation(fadeIn);
     99     }
    100     
    101   }
    102  
    103   void bookmarkListItemClicked(Bookmark selectedBookmark) {
    104     clipboardManager.setText(selectedBookmark.getUrl());
    105   }
    106  
    107 }

    使用后:

     1 @NoTitle
     2 @Fullscreen
     3 @EActivity(R.layout.bookmarks)
     4 public class BookmarksToClipboardActivity extends Activity {
     5   
     6   BookmarkAdapter adapter;
     7   
     8   @ViewById
     9   ListView bookmarkList;
    10  
    11   @ViewById
    12   EditText search;
    13   
    14   @App
    15   BookmarkApplication application;
    16   
    17   @RestService
    18   BookmarkClient restClient;
    19  
    20   @AnimationRes
    21   Animation fadeIn;
    22   
    23   @SystemService
    24   ClipboardManager clipboardManager;
    25  
    26   @AfterViews
    27   void initBookmarkList() {
    28     adapter = new BookmarkAdapter(this);
    29     bookmarkList.setAdapter(adapter);
    30   }
    31   
    32   @Click({R.id.updateBookmarksButton1, R.id.updateBookmarksButton2})
    33   void updateBookmarksClicked() {
    34     searchAsync(search.getText().toString(), application.getUserId());
    35   }
    36   
    37   @Background
    38   void searchAsync(String searchString, String userId) {
    39     Bookmarks bookmarks = restClient.getBookmarks(searchString, userId);
    40     updateBookmarks(bookmarks);
    41   }
    42  
    43   @UiThread
    44   void updateBookmarks(Bookmarks bookmarks) {
    45     adapter.updateBookmarks(bookmarks);
    46     bookmarkList.startAnimation(fadeIn);
    47   }
    48   
    49   @ItemClick
    50   void bookmarkListItemClicked(Bookmark selectedBookmark) {
    51     clipboardManager.setText(selectedBookmark.getUrl());
    52   }
    53  
    54 }
    1 @Rest("http://www.bookmarks.com")
    2 public interface BookmarkClient {
    3   
    4   @Get("/bookmarks/{userId}?search={search}")
    5   Bookmarks getBookmarks(String search, String userId);
    6  
    7 }

    且利用androidannotations的Rest注解替换手工建立Spring Android RestTemplate对象,不仅可以减少很多代码,同时使工程结构更简洁、严谨,利于复用。

    自己构造RestTemplate的原生写法:

     1 HttpHeaders requestHeaders = new HttpHeaders();  
     2 List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();  
     3 acceptableMediaTypes.add(MediaType.APPLICATION_JSON);  
     4 requestHeaders.setAccept(acceptableMediaTypes);  
     5                   
     6 HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);  
     7                   
     8 RestTemplate restTemplate = new RestTemplate();  
     9 restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());  
    10                   
    11 ResponseEntity<User[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, User[].class);  

    利用androidannotations的Rest注解替换后的代码:

    1 //初始化
    2 @RestService  
    3 RestApiService restApiService;
    4 ResponseEntity<User[]> responseEntity = restApiService.getByStatus(); 
    1 @Rest(rootUrl = "http://10.0.2.2:8080/together/api", converters = { MappingJackson2HttpMessageConverter.class })  
    2 public interface RestApiService {  
    3       
    4     @Get("/user/getByStatus.do?status=1")  
    5     ResponseEntity<User[]> getUsersByStatus();  
    6   
    7 }  

    wiki api :

    https://github.com/excilys/androidannotations/wiki/Rest-API

  • 相关阅读:
    HDU 5319 Painter
    HDU 5328 Problem Killer
    HDU 5327 Olympiad
    HDU 5339 Untitled
    HDU 5335 Walk Out
    HDU 5317 RGCDQ
    HDU 5326 Work
    CF GYM 100703A Tea-drinking
    CF GYM 100703B Energy Saving
    CF GYM 100703F Game of words
  • 原文地址:https://www.cnblogs.com/CharlesGrant/p/4737272.html
Copyright © 2020-2023  润新知