从回调更新类字段

时间:2015-04-23 00:31:18

标签: java android retrofit

我尝试使用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);
}
}

1 个答案:

答案 0 :(得分:1)

您可以尝试使用回调:

示例:

From

在活动/片段中

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.
            }
        });
    }    
}

}