无法使用改型默认回调从API显示图像和文本

时间:2018-10-03 11:29:13

标签: android retrofit2

我是Android开发领域的新手,我制作了一个集会简单的应用,该应用在翻新的帮助下从http://api.tvmaze.com/search/shows?q=girls加载了一些图像和文本 应用程序未显示任何项目,我也不知道出了什么问题 这是我的代码:

渐变应用

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'

implementation 'com.android.support:design:28.0.0'

implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'


// https://github.com/ReactiveX/RxAndroid
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.10'

//Retrofit http://square.github.io/retrofit
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

// GSON body parser
implementation 'com.google.code.gson:gson:2.8.2'

//Glide
implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'

testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

响应:

{
"score": 17.220499,
"show": {
  "id": 139,
  "url": "http://www.tvmaze.com/shows/139/girls",
  "name": "Girls",
  "type": "Scripted",
  "language": "English",
  "genres": [
    "Drama",
    "Romance"
  ],
  "status": "Ended",
  "runtime": 30,
  "premiered": "2012-04-15",
  "officialSite": "http://www.hbo.com/girls",
  "schedule": {
    "time": "22:00",
    "days": [
      "Sunday"
    ]
  },
  "rating": {
    "average": 6.7
  },
  "weight": 94,
  "network": {
    "id": 8,
    "name": "HBO",
    "country": {
      "name": "United States",
      "code": "US",
      "timezone": "America/New_York"
    }
  },
  "webChannel": null,
  "externals": {
    "tvrage": 30124,
    "thetvdb": 220411,
    "imdb": "tt1723816"
  },
  "image": {
    "medium": "http://static.tvmaze.com/uploads/images/medium_portrait/31/78286.jpg",
    "original": "http://static.tvmaze.com/uploads/images/original_untouched/31/78286.jpg"
  },
  "summary": "<p>This Emmy winning series is a comic look at the assorted humiliations and rare triumphs of a group of girls in their 20s.</p>",
  "updated": 1538265422,
  "_links": {
    "self": {
      "href": "http://api.tvmaze.com/shows/139"
    },
    "previousepisode": {
      "href": "http://api.tvmaze.com/episodes/1079686"
    }
  }
 }
}

这是我模块的类(每个类在不同的文件中)

public class Image {

@SerializedName("medium")
@Expose
private String medium;
@SerializedName("original")
@Expose
private String original;

public String getMedium() {
    return medium;
}

public void setMedium(String medium) {
    this.medium = medium;
}

public String getOriginal() {
    return original;
}

public void setOriginal(String original) {
    this.original = original;
 }
 }

public class Movie {
@SerializedName("name")
@Expose
private String name;
@SerializedName("image")
@Expose
private Image image;
@SerializedName("summary")
@Expose
private String summary;

public String getTitle() {
    return name;
}

public void setTitle(String name) {
    this.name = name;
}
public Image getImageUrl() {
    return image;
}

public void setImageUrl(Image image)
{
    this.image = image;
}

public String getSummary() {
    return summary;
}
public void setSummary(String summary) {
    this.summary = summary;
}
}


public class MovieResponse {
@SerializedName("show")
@Expose
private Movie show;

public Movie getShow() {
    return show;
}
}

适配器:

public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.MyViewHolder> {

private List<MovieResponse> movieList;
//private List<MovieResponse> movieListFiltered;
private Context context;

public void setMovieList(Context context,final List<MovieResponse> movieList){
    this.context = context;
    this.movieList = movieList;
}

@Override
public MovieAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,parent,false);
    return new MyViewHolder(view);
}

@Override
public void onBindViewHolder(MovieAdapter.MyViewHolder holder, int position) {
    holder.title.setText(movieList.get(position).getShow().getTitle());
    holder.summary.setText(movieList.get(position).getShow().getSummary());
    GlideApp.with(context).load(movieList.get(position).getShow().getImageUrl().getMedium()).listener(new RequestListener() {
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
            // Log the GlideException here (locally or with a remote logging framework):
            Log.e(TAG, "Load failed", e);
            Toast.makeText(context,"error", Toast.LENGTH_SHORT).show();

            // You can also log the individual causes:
            for (Throwable t : e.getRootCauses()) {
                Log.e(TAG, "Caused by", t);
                Toast.makeText(context,t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
            // Or, to log all root causes locally, you can use the built in helper method:
            e.logRootCauses(TAG);

            return false; // Allow calling onLoadFailed on the Target.
        }

        @Override
        public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
            // Log successes here or use DataSource to keep track of cache hits and misses.

            return false; // Allow calling onResourceReady on the Target.

        }

    }).into(holder.image);
}

@Override
public int getItemCount() {

    if(movieList != null){
        return movieList.size();
    } else {
        return 0;
    }
}


public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView title, summary;
    ImageView image;

    public MyViewHolder(View view) {
        super(view);
        title = (TextView) view.findViewById(R.id.title);
        image = (ImageView)view.findViewById(R.id.image);
        summary=(TextView)view.findViewById(R.id.summary);
    }
}
}

主要活动

public class MainActivity extends AppCompatActivity {
//private SearchView searchView;
private RecyclerView recyclerView;
private MovieAdapter movieAdapter;
private List<MovieResponse> movieList;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    movieList = new ArrayList<>();
    recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    movieAdapter = new MovieAdapter();
    recyclerView.setAdapter(movieAdapter);


  ApiInterface apiService = TvMazeApiClient.getClient().create(ApiInterface.class);
  Call <List<MovieResponse>> call = apiService.getMovies("girls");

    call.enqueue(new Callback<List<MovieResponse>>() {
        @Override
        public void onResponse(Call<List<MovieResponse>> call, Response<List<MovieResponse>> response) {
            if(movieList != null) {
                movieList = response.body();
                Log.d("TAG", "Response = " + movieList);
                movieAdapter.setMovieList(getApplicationContext(), movieList);
            }
            else{
                Toast.makeText(MainActivity.this,"error", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<List<MovieResponse>> call, Throwable t) {
            Log.d("TAG","Response = "+t.toString());
            Toast.makeText(MainActivity.this,t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }
    });

}

}

Api客户端

public class TvMazeApiClient {

    public static String BASE_URL ="http://api.tvmaze.com/";
    private static Retrofit retrofit;

public void TvMazeApiClient(){

}
    public static Retrofit getClient(){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

 }

Api界面

public interface ApiInterface {
@GET("search/shows")
Call<List<MovieResponse>> getMovies(@Query("q")  String query);
}

请给我一些建议怎么做

1 个答案:

答案 0 :(得分:0)

movieList中添加新数据后,您需要使用notifyDataSetChanged();

  • 通知所有注册的观察者该数据集已更改。

尝试一下

public void setMovieList(Context context,final List<MovieResponse> movieList){
    this.context = context;
    this.movieList = movieList;
    notifyDataSetChanged();
}