我試圖用MOVIE db API獲取的數據更新我的回收視圖。我使用ASYNC任務來發出請求並從服務器獲取結果,但是在onPostExecute()中,當我嘗試清除適配器並將新數據添加到適配器時,它顯示「無法解析方法」clear()' 「無法在Recyclerview中解析方法「clear()」
MAINACTIVITY
public class MainActivity extends AppCompatActivity {
final static QueryUtils queryUtils = new QueryUtils();
final static String URL = "http://api.themoviedb.org/3/movie/popular? api_key=";
static String[] finalData = new String[queryUtils.getLengthOfJsonArray(URL)];
public RecyclerView mRecyclerView;
public RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recylerView);
//using the grid layout manager
mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
mRecyclerView.setLayoutManager(mLayoutManager);
//setting the adpater.
mAdapter = new MovieAdapter(finalData, this);
mRecyclerView.setAdapter(mAdapter);
MovieTask task =new MovieTask();
task.execute(URL);
}
private class MovieTask extends AsyncTask<String, Void, String[]> {
@Override
protected String[] doInBackground(String... params) {
String[] data = queryUtils.fetchMovieData(URL);
return data;
}
@Override
protected void onPostExecute(String[] data) {
mAdapter.clear();
}
}
}
MOVIE-ADAPTER胡亞蓉
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder>{
private String[] adumyString;
private int[] adumyimage;
private Context context;
//Constructor for Movie Adapter
public MovieAdapter(String[] dummyDataSet,Context context) {
this.context=context;
adumyString=dummyDataSet;
}
// Provide a direct reference to each of the views within a data item
// Used to cache the views within the item layout for fast access
public static class ViewHolder extends RecyclerView.ViewHolder {
// Your holder should contain a member variable
// for any view that will be set as you render a row
public ImageView colorImageView;
// We also create a constructor that accepts the entire item row.
// and does the view lookups to find each subview
public ViewHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
colorImageView = (ImageView) itemView.findViewById(R.id.movieImage);
}
}
/**
* Binds the data into
*/
@Override
public void onBindViewHolder(MovieAdapter.ViewHolder holder, int position) {
Picasso.with(context).load(adumyString[position]).into(holder.colorImageView);
}
@Override
public int getItemCount() {
return adumyString.length;
}
/**
* Inflates the out custom view on to the screen.
*/
@Override
public MovieAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_view,parent,false);
return new ViewHolder(v);
}
}
RecyclerView.Adapter沒有clear()方法。你必須在使用之前執行它 –