2015-04-23 51 views
0

我試圖使用Retrofit連接到API。我需要登錄用戶,並在此集"user"字段中包含所有其他API調用所需的會話密鑰。所以我需要在執行任何代碼之前使它可用,但我不知道如何檢查或阻止代碼,直到該字段將被設置。任何想法如何做到這一點?從回調中更新類字段

public class ApiClient { 

public static final String developerKey = ""; 
public static final String applicationKey = ""; 

static final String BASE_URL = 
     "https://secure.techfortesco.com/tescolabsapi"; 

public ApiService mApiService; 
public User user; 

public ApiClient() { 
    RestAdapter restAdapter = new RestAdapter.Builder() 
      .setLogLevel(RestAdapter.LogLevel.FULL) 
      .setEndpoint(BASE_URL) 
      .build(); 

    if(mApiService == null) { 
     mApiService = restAdapter.create(ApiService.class); 
    } 
} 

public void login() { 

    mApiService.login(developerKey, applicationKey, new Callback<User>() { 

     @Override 
     public void success (User user, Response response) { 
      //code which should update user field 
     } 

     @Override 
     public void failure (RetrofitError error) { 

     } 

    }); 
} 

public interface ApiService { 

    @GET ("/restservice.aspx?command=LOGIN&email=&password=") 
    public void login (
      @Query ("developerkey") String developerKey, 
      @Query ("applicationkey") String applicationKey, 
      Callback<User> callback); 

    @GET ("/restservice.aspx?command=PRODUCTSEARCH") 
    public void search (
      @Query ("searchtext") String searchText, 
      @Query ("sessionkey") String sessionKey, 
      Callback<Pojo.SearchResult> callback); 
} 
} 
+0

這真的取決於您的使用情況。誰在調用登錄名,以及何時在Api中調用另一個請求? –

+0

我的回答對你有幫助嗎?如果有幫助,請標記爲正確。 –

回答

1

您可以嘗試使用回調:

例子:

public interface LoginCallback { 
    void ready(); 
} 

而且在活動/片段

public MainActivity extends Activity { 

    public void onCreate() { 
     super.onCreate(); 
     ApiClient client = new ApiClient(); 
     client.login(new LoginCallback() { 
      @Override 
      public void ready() { 
      //... do your next request in the API. 
      } 
     }); 
    }  
} 

和你的登錄方法變成了:

public void login(final LoginCallback loginCallback) { 

mApiService.login(developerKey, applicationKey, new Callback<User>() { 

    @Override 
    public void success (User user, Response response) { 
     //code which should update user field 
     loginCallback.ready(); 
    } 

    @Override 
    public void failure (RetrofitError error) { 

    } 

}); 

}