我的Retrofit call.enque()方法完全被跳过,不知道为什么

时间:2017-08-15 23:54:15

标签: java android json rest retrofit

我正在使用Retrofit的enqueue()方法拨打电话。我在我的MainActivity refreshImages()onCreate()中调用我的refreshImages()然后调用方法refreshImagesIds(),该方法应该调用Flickr的API并返回{{1} 1}}对象,然后我将从那里拉出PhotosList,其中包含Photos个对象的列表。我的问题是,出于某种原因,我的Photo方法中的onResponse()永远不会被调用。当我使用调试器时,它会跳过它,当我将Log语句放入其中时,它们永远不会被写出来。我知道它正在击中的端点是正确的,因为我可以使用OkHttp的记录器看到它,并且我的POJO看起来对于返回的数据都是正确的。

知道为什么这不起作用?以下是我的enqueue()refreshImages。这些都包含在我的MainAcitivty中并修改了类级变量。

refreshImagesId

我的FlickrServiceInterface:

private void refreshImages() {
        // make api call
        //imageUrls = FlickrServiceManager_withinterface.getKittenImages(8);

        refreshImageIds();

        List<Photo> photos = photosList.getPhotos().getPhoto();
        imageIds = new ArrayList<String>();
        for(Photo photo : photos) {
            Log.d("TAG", "It is pringint imageIds: " + photo.getId());
            imageIds.add(photo.getId());
        }
}

private void refreshImageIds() {
    Retrofit retrofit = Api.getRestAdapter();
    FlickrServiceInterface flickrService = retrofit.create(FlickrServiceInterface.class);
    Call<PhotosList> call = flickrService.getPhotos(API_KEY, FORMAT, "1");
    imageIds = new ArrayList<String>();

    call.enqueue(new Callback<PhotosList>(){
        @Override
        public void onResponse(Call<PhotosList> call, Response<PhotosList> response) {
            photosList = response.body();
        }

        @Override
        public void onFailure(Call<PhotosList> call, Throwable t) {
            // TODO: Clean up
            Log.d("TEMP_TAG", "Call failed");
        }
    });
}

2 个答案:

答案 0 :(得分:2)

将您的呼叫更改为同步改造API:

AsyncTask

请注意,您需要在//interface por communication public interface ImageIdsCallBack { public void onFinish( List<String> photoIds ); }

上调用此方法

编辑

你也可以继续使用enqueue,但你需要提供一个&#34; onFinish&#34;钩子,所以你知道你的数据何时被收到然后你通知&#34;客户端有数据:

public static List<String> getImageIds(int size, final ImageIdsCallBack callback) {
    Call<PhotosList> call = flickrService.getPhotos(apiKey, format, "1");
    photoIds = new ArrayList<String>();

    call.enqueue(new Callback<PhotosList>(){
        @Override
        public void onResponse(Call<PhotosList> call, Response<PhotosList> response) {
            PhotosList photosList = response.body();
            List<Photo> photos = photosList.getPhotos().getPhoto();

            for(Photo photo : photos) {
                Log.d("TEMP_TAG", "adding photo id to list: " + photo.getId());
                photoIds.add(photo.getId());
            }
            //send the data to the caller
            callback.onFinish(photoIds);
        }

        @Override
        public void onFailure(Call<PhotosList> call, Throwable t) {
            // TODO: Clean up
            Log.d("TEMP_TAG", "Call failed");
        }
    });
    Log.d("TEMP_TAG", "it's getting here too");
    return photoIds;
}

然后您会收到此界面并发送数据:

getImageIds( 50 , new ImageIdsCallBack() {
     public void onFinish( List<String> photoIds ) {
         //update UI with photoIds
     }
} );

调用方法:

@Configuration
@Profile({ "neo" })
@EnableTransactionManagement
public class DataSourceNeoConfig {

@Bean
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
    final JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();

    DataSource dataSource = dataSourceLookup.getDataSource("java:comp/env/jdbc/DefaultDB");

    return dataSource;
}

@Bean
public JpaVendorAdapter jpaVendorAdapter() {
    EclipseLinkJpaVendorAdapter jpaVendorAdapter = new EclipseLinkJpaVendorAdapter();
    jpaVendorAdapter.setGenerateDdl(true);
    jpaVendorAdapter.setShowSql(true);

    return jpaVendorAdapter;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

    LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();

    try {
        lef.setDataSource(jndiDataSource());
    } catch (IllegalArgumentException | NamingException e) {
        e.printStackTrace();
    }

    lef.setJpaVendorAdapter(jpaVendorAdapter());

    Properties properties = new Properties();
    properties.setProperty("eclipselink.weaving", "false");
    properties.setProperty(PersistenceUnitProperties.LOGGING_LEVEL, "FINE");
    properties.setProperty("eclipselink.ddl-generation", "create-tables");
// eclipselink.tenant.id is column the identifier in mapped class
// @TenantDiscriminatorColumn(name = "TENANT_ID", contextProperty = "eclipselink.tenant.id", length = 36)
    properties.setProperty("eclipselink.tenant.id", TenantHolder.getTenant());

    lef.setPackagesToScan("com.strongit.models");
    lef.setJpaProperties(properties);
    lef.afterPropertiesSet();
    return lef;
}

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
  JpaTransactionManager transactionManager = new JpaTransactionManager();
  transactionManager.setEntityManagerFactory(emf);

  return transactionManager;
}
}

我通常使用像EventBus这样的库来简化它,我真的推荐给你。

答案 1 :(得分:0)

如果我错了,请纠正我,这是主线程吗?这会造成不等待回应的问题。

考虑使用async