4

我有一個存儲在雲中,與谷歌應用程序引擎的Android應用程序。我使用雲端點。我的問題是我無法將數據從服務器發送到我的客戶端(Android設備),或者更好地說,到目前爲止,我不知道該怎麼做。如何從服務器端(谷歌應用程序引擎,雲端點)的信息,我的客戶送?

到目前爲止,我已經設法通過創建一個端點並調用負責在數據庫中添加一條記錄(位於服務器端,位於myProject-AppEngine中)的方法來在數據存儲中插入數據,使用下面的代碼(在客戶端上):\

Noteendpoint.Builder endpointBuilder = new Noteendpoint.Builder(
AndroidHttp.newCompatibleTransport(), 
new JacksonFactory(), 
new HttpRequestInitializer() { 
public void initialize(HttpRequest httpRequest) { } 
}); 
    Noteendpoint endpoint = CloudEndpointUtils.updateBuilder(
    endpointBuilder).build(); 
    try { 
     // Construct the note. 
     Note note = new Note().setDescription("Note DescriptionRoxana"); 
     String noteID = new Date().toString(); 
     note.setId(noteID); 

     note.setEmailAddress("E-Mail AddressRoxana");   
     // Insert the Note, by calling a method that's on the server side - insertNote(); 
     Note result = endpoint.insertNote(note).execute(); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 

但我不能看到從數據存儲中檢索數據的方法,並在服務器端顯示它。我試圖做同樣的事情,創建一個端點,它將調用檢索數據庫中所有記錄的方法(位於服務器上的方法),但是我的應用程序崩潰。

爲從數據庫中檢索數據的方法的代碼如下:

public CollectionResponse<Note> listNote(
     @Nullable @Named("cursor") String cursorString, 
     @Nullable @Named("limit") Integer limit) { 

    EntityManager mgr = null; 
    Cursor cursor = null; 
    List<Note> execute = null; 

    try { 
     mgr = getEntityManager(); 
     Query query = mgr.createQuery("select from Note as Note"); 
     if (cursorString != null && cursorString != "") { 
      cursor = Cursor.fromWebSafeString(cursorString); 
      query.setHint(JPACursorHelper.CURSOR_HINT, cursor); 
     } 

     if (limit != null) { 
      query.setFirstResult(0); 
      query.setMaxResults(limit); 
     } 

     execute = (List<Note>) query.getResultList(); 
     cursor = JPACursorHelper.getCursor(execute); 
     if (cursor != null) 
      cursorString = cursor.toWebSafeString(); 

     // Tight loop for fetching all entities from datastore and accomodate 
     // for lazy fetch. 
     for (Note obj : execute) 
      ; 
    } finally { 
     mgr.close(); 
    } 

    return CollectionResponse.<Note> builder().setItems(execute) 
      .setNextPageToken(cursorString).build(); 
} 

你看,返回類型是集合響應。您可以訪問這種類型的數據,執行以下導入後:

import com.google.api.server.spi.response.CollectionResponse; 

我推斷,這是一種數據類型的特性到服務器端,因此,我不知道我怎麼能丟在一個列表,ArrayList或任何其他類型的集合,可以在客戶端使用。

我應該如何去做呢?由於添加數據非常簡單且直截了當,因此我認爲檢索數據將以相同的方式執行,但顯然我缺少對此事重要的東西。

預先感謝您!

回答

4

您在後端使用的類不一樣的,你會在客戶端使用的類。端點將爲您生成一組庫,可以通過命令行或使用Google Plugin for Eclipse等工具。見Using Endpoints in an Android Client

在您的示例中代表集合Note的生成類將被命名爲NotesCollection。這個對象有一個方法getItems,爲您提供一個List<Note>,你可以在你的Android應用程序上進行迭代。

0

具有用於插入數據的數據存儲模型(Post類型的方法)端點類似,你需要有一個端點從數據存儲模型(類型GET方法)查詢數據。在定義這兩種方法之後,您需要生成發現文檔和客戶端庫,以便客戶端了解這兩種方法並且可以調用它們。如果您說到在網絡中顯示數據本身,那麼您可以通過使用所需的客戶端庫來構建Javascript client

相關問題