I can't get my code work
I'm trying to get a list of my database activities.
A lot of research here and none of the answers helped me
My Adapter
public class AtividadesAdapter extends RecyclerView.Adapter<AtividadesAdapter.AtividadesViewHolder> {
private Context mCtx;
private List<Atividades> atividadesList;
public AtividadesAdapter(Context mCtx, List<Atividades> atividadesList) {
this.mCtx = mCtx;
this.atividadesList = atividadesList;
}
#Override
public AtividadesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.atividades_lista, null);
return new AtividadesViewHolder(view);
}
#Override
public void onBindViewHolder(AtividadesViewHolder holder, int position) {
Atividades atividades = atividadesList.get(position);
holder.textViewAtividade.setText(atividades.getAtividade());
holder.textViewData.setText(String.valueOf(atividades.getDataPrevista()));
holder.textViewHora.setText(String.valueOf(atividades.getHora()));
holder.textViewDestinatarios.setText(atividades.getDestinatarios());
}
#Override
public int getItemCount() {
return atividadesList.size();
}
class AtividadesViewHolder extends RecyclerView.ViewHolder {
TextView textViewAtividade, textViewData, textViewHora, textViewDestinatarios;
public AtividadesViewHolder(View itemView) {
super(itemView);
textViewAtividade = itemView.findViewById(R.id.textViewAtividade);
textViewData = itemView.findViewById(R.id.textViewData);
textViewHora = itemView.findViewById(R.id.textViewHora);
textViewDestinatarios = itemView.findViewById(R.id.textViewDestinatarios);
}
}
}
My activity
public class AtividadesActivity extends AppCompatActivity {
private static final String URL_ATIVIDADES = "";
List<Atividades> atividadesList = new ArrayList<>();
public RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.atividadesrecyclerview);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
loadAtividades();
}
private void loadAtividades() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_ATIVIDADES,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject a = array.getJSONObject(i);
Log.d("Valores", a.getString("Atividade"));
atividadesList.add(new Atividades(
a.getInt("idAtividade"),
a.getString("Atividade"),
java.sql.Date.valueOf(a.getString("dataPrevista")),
java.sql.Time.valueOf(a.getString("hora")),
a.getString("Destinatarios"),
a.getString("Local")
));
}
AtividadesAdapter mAdapter = new AtividadesAdapter(AtividadesActivity.this, atividadesList);
recyclerView.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(this).add(stringRequest);
}
}
Everytime i'm trying to start the app, i get this error.
I have already change the xml files to match with the examples provided here but still have no success.
Please attach parent and the rest:
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
return new AtividadesViewHolder(LayoutInflater.from(mCtx).inflate(R.layout.atividades_lista, parent, false));
}
Based on your question and the code I think this will help you.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.atividadesrecyclerview);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
AtividadesAdapter mAdapter = new AtividadesAdapter(getApplicationContext, atividadesList);
recyclerView.setAdapter(mAdapter);
loadAtividades();
}
Add to your adapter:
public AtividadesAdapter(Context mCtx) {
this.mCtx = mCtx;
}
public void setItems(#NonNull final List<Atividades> items) {
if (atividadesList != null) {
atividadesList.clear();
} else {
atividadesList = new ArrayList<>();
}
atividadesList.addAll(items);
}
onCreate of the activity should be as follows:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.atividadesrecyclerview);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
mAdapter = new AtividadesAdapter(AtividadesActivity.this);
recyclerView.setAdapter(mAdapter);
loadAtividades();
}
In loadAtividades() call to setItems:
mAdapter.setItems(atividadesList);
Related
When I am writing the title of my question, then this site recommends me some answer but I can't find my answer that's why I am writing a new one. I am trying simple RecyclerView and it's run successfully but when I am fetching data from internet using volley library then I face this error
here is my code
BusinessActivity.java
public class BusinessActivity extends AppCompatActivity {
private final String URL = "https://api.myjson.com/bins/a44ec";
private JsonArrayRequest request;
private RequestQueue requestQueue;
private List<ArticleModel> articleList;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business);
articleList = new ArrayList<>();
recyclerView = findViewById(R.id.business_recyclerView);
jsonParse();
}
private void jsonParse() {
request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i=0;i<response.length();i++){
try {
jsonObject = response.getJSONObject(i);
ArticleModel article = new ArticleModel();
article.setTitle(jsonObject.getString("title"));
article.setAuthor(jsonObject.getString("author"));
article.setDescription(jsonObject.getString("description"));
article.setPublishedAt(jsonObject.getString("publishedAt"));
article.setUrlToImage(jsonObject.getString("urlToImage"));
articleList.add(article);
} catch (JSONException e) {
e.printStackTrace();
}
}
setRecyclerView(articleList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(BusinessActivity.this);
requestQueue.add(request);
}
private void setRecyclerView(List<ArticleModel> articleList) {
BusinessAdapter adapter = new BusinessAdapter(articleList,this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
}
BusinessAdapter.java
public class BusinessAdapter extends RecyclerView.Adapter<BusinessAdapter.MyViewHolder> {
private List<ArticleModel> articleModels;
private Context context;
RequestOptions options;
public BusinessAdapter(List<ArticleModel> articleModels, Context context) {
this.articleModels = articleModels;
this.context = context;
options = new RequestOptions().centerCrop().placeholder(R.drawable.ic_launcher_background).error(R.drawable.ic_launcher_background);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.category_row,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
ArticleModel articleModel = articleModels.get(position);
holder.title.setText(articleModel.getTitle());
holder.author.setText(articleModel.getAuthor());
holder.desc.setText(articleModel.getDescription());
holder.date.setText(articleModel.getPublishedAt());
Glide.with(context).load(articleModel.getUrlToImage()).apply(options).into(holder.image);
}
#Override
public int getItemCount() {
return articleModels.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView title,author,desc,date;
ImageView image;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title);
author = itemView.findViewById(R.id.author);
desc = itemView.findViewById(R.id.detail);
date = itemView.findViewById(R.id.date);
image = itemView.findViewById(R.id.image);
}
}
}
Error log
2020-04-01 00:15:53.117 8821-8821/com.atc.newsappproject E/RecyclerView: No adapter attached; skipping layout
2020-04-01 00:15:53.118 1752-1787/? E/storaged: getDiskStats failed with result NOT_SUPPORTED and size 0
How can I solve this?
Thank you.
This error usually happens when you don't set the RecyclerView when you create your Fragment or Activity. To fix this you need to:
Set your RecyclerView in onCreate instead of when you pick up result. You set it with an empty list.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business);
articleList = new ArrayList<>();
recyclerView = findViewById(R.id.business_recyclerView);
setRecyclerView(articleList);
jsonParse();
}
You create a setter in your Adapter
public void setArticles(ArrayList<ArticleModel> articles){
this.articles = articles;
notifyDataSetChanged();
}
Create private BusinessAdapter adapter; below private RecyclerView recyclerView;
Finally in your onResponse you call adapter.setArticles(articlesList);
Here is a link with a lot of solutions if you still got issue: recyclerview No adapter attached; skipping layout
It gives me a blank activity and not showing my list in it .. i don't know what is the error.Any one who can help ?
Here is my code:
public class Home extends AppCompatActivity implements HomeCallBack {
public ArrayList<info> info;
private Adaptor myadaptor;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
recyclerView=(RecyclerView)findViewById(R.id.recycle_view);
BackgroundHome backgroundHome=new BackgroundHome(this,this);
backgroundHome.execute();
}
#Override
public void processData(JSONArray data)
{
JSONObject js;
if(data!=null)
{
info=new ArrayList<>();
try
{
for(int i=0;i<data.length();i++)
{
js =data.getJSONObject(i);
info in=new info(js.getString("Names"),js.getString("city"),js.getString("university"));
info.add( in);
}
myadaptor=new Adaptor(info);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter( myadaptor);
It gives me an error and app stop when i call recyclerView.setAdapter(myadapter) in on create method.
Here is my adaptor code:
public class Adaptor extends RecyclerView.Adapter<Adaptor.ViewHolder> {
private ArrayList<info> info;
public Adaptor(ArrayList<info> info) {
this.info = info;
}
public void updateList(ArrayList<info> data) {
info = data;
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_view, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
info i= info.get(position);
holder.name.setText(i.getName());
holder.city.setText(i.getCity());
holder.city.setText(i.getUniversity());
}
#Override
public int getItemCount() {
return info.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name, city, uni;
public ViewHolder(final View v) {
super(v);
name = (TextView) v.findViewById(R.id.name);
city = (TextView) v.findViewById(R.id.city);
uni = (TextView) v.findViewById(R.id.university);
}
}
}
This is my adaptor class and above is my Home activity where am trying to show my list
I think the problem is that you try to set the adapter outside of main thread. you should use this code:
#Override
public void processData(JSONArray data)
{
JSONObject js;
if(data!=null)
{
info=new ArrayList<>();
try
{
for(int i=0;i<data.length();i++)
{
js =data.getJSONObject(i);
info in=new info(js.getString("Names"),js.getString("city"),js.getString("university"));
info.add( in);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
myadaptor=new Adaptor(info);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter( myadaptor);
}
});
Try initializing your adapter, recyclerview and layoutmanager in onCreate. And then when your call in processData is finished get the list and call mAdapter.notifyDataSetChanged.
public class Home extends AppCompatActivity implements HomeCallBack {
public ArrayList<info> info;
private Adaptor myadaptor;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
recyclerView=(RecyclerView)findViewById(R.id.recycle_view);
info = new ArrayList<>();
myadaptor=new Adaptor(info);
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(myadaptor);
BackgroundHome backgroundHome=new BackgroundHome(this,this);
backgroundHome.execute();
}
#Override
public void processData(JSONArray data) {
JSONObject js;
if(data!=null) {
try {
for(int i=0; i<data.length(); i++)
{
js = data.getJSONObject(i);
info in = new info(js.getString("Names"),js.getString("city"),js.getString("university"));
info.add(in);
}
myadaptor.notifyDataSetChanged();
I have a full working project but would like to write an espresso test for the main activity which basically test for counting recyclerview items, the code consume JSON values and pass a list to an adapter with the help of recycler view to display. I had a test written but i kept on getting null objects as response and it fails below are the codes
MainActivity.class
public class MainActivity extends AppCompatActivity implements RecipeTestDownloader.DelayerCallback {
private RecyclerView recyclerView;
ProgressDialog pd;
List<Recipe> recipes;
private static Context mContext;
#Nullable
private SimpleIdlingResource mIdlingResource;
#VisibleForTesting
#NonNull
public IdlingResource getIdlingResource() {
if (mIdlingResource == null) {
mIdlingResource = new SimpleIdlingResource();
}
return mIdlingResource;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_list);
initViews();
mContext = this;
RecipeSyncUtils.initialize(this);
getIdlingResource();
}
public Activity getActivity(){
Context context = this;
while (context instanceof ContextWrapper){
if (context instanceof Activity){
return (Activity) context;
}
context = ((ContextWrapper) context).getBaseContext();
}
return null;
}
private void initViews(){
boolean isPhone = getResources().getBoolean(R.bool.is_phone);
if (isPhone) {
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
} else {
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
}
}
RecipeSyncUtils.initialize(this);
loadJSON();
}
private void loadJSON(){
Service serviceAPI = Client.getClient();
Call<JsonArray> loadRecipeCall = serviceAPI.readRecipeArray();
loadRecipeCall.enqueue(new Callback<JsonArray>() {
#Override
public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {
try {
String recipeString = response.body().toString();
Type listType = new TypeToken<List<Recipe>>() {}.getType();
recipes = JsonUtils.getRecipeListFromJson(recipeString, listType);
recyclerView.setAdapter(new RecipeAdapter(getApplicationContext(), recipes));
recyclerView.smoothScrollToPosition(0);
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Call<JsonArray> call, Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
#Override
protected void onStart() {
super.onStart();
RecipeTestDownloader.downloadRecipe(this, MainActivity.this, mIdlingResource);
}
#Override
public void onDone(ArrayList<Recipe> recipes) {
}
}
RecipeAdapter.class
public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.MyViewHolder> {
private Context mContext;
private List<Recipe> recipeList;
public RecipeAdapter(Context mContext, List<Recipe> objects){
this.mContext = mContext;
this.recipeList = objects;
}
#Override
public RecipeAdapter.MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i){
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recipe_card, viewGroup, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final RecipeAdapter.MyViewHolder viewHolder, int i){
viewHolder.title.setText(recipeList.get(i).getName());
String thumbnail = recipeList.get(i).getImage();
Glide.with(mContext)
.load(thumbnail)
.into(viewHolder.image);
}
#Override
public int getItemCount(){
return recipeList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView title;
ImageView image;
public MyViewHolder(View view){
super(view);
title = (TextView) view.findViewById(R.id.item_title);
image = (ImageView) view.findViewById(R.id.recipeImage);
view.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION){
Recipe clickedDataItem = recipeList.get(pos);
Intent intent = new Intent(mContext, RecipeDetailActivity.class);
intent.putExtra("Recipe", clickedDataItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
Toast.makeText(v.getContext(), "You clicked " + clickedDataItem.getName(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
I need help on how to write the espresso test on this MainActivty i.e getItemCount test, text matcher or any test implementation
Fragment_bookmovie2.java
public class Fragment_bookmovie2 extends android.support.v4.app.Fragment implements View.OnClickListener {
private static final String TAG ="Fragment_bookmovie2" ;
ArrayList<String> moviename= new ArrayList<>();
ArrayList<String> movieyear= new ArrayList<>();
ArrayList<String> moviebanner= new ArrayList<>();
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
Movie_listAdapter2 adapter ;
LinearLayout progress;
RelativeLayout ll;
public Fragment_bookmovie2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Log.e(TAG,"reched on create");
// first step - retrieve object
Backendless.Persistence.of(Booking.class).find(new AsyncCallback<BackendlessCollection<Booking>>() {
#Override
public void handleResponse(BackendlessCollection<Booking> response) {
for(Booking booking : response.getData()) {
if(!moviename.contains(booking.getMovie().get(0).getMovie_Name())) {
moviename.add(booking.getMovie().get(0).getMovie_Name());
movieyear.add(booking.getMovie().get(0).getYear());
moviebanner.add("https://api.backendless.com/" + BackendSetting.APPLICATION_ID + "/" + BackendSetting.VERSION + "/files/mypics/" + booking.getMovie().get(0).getImage());
}
}
adapter.notifyDataSetChanged();
ll.removeView(progress);
}
#Override
public void handleFault(BackendlessFault fault) {
Toast.makeText(getActivity(), fault.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
moviename.add("haha");
movieyear.add("hello");
moviebanner.add("http://www.w3schools.com/css/trolltunga.jpg");
// Inflate the layout for this fragment
ll = (RelativeLayout) inflater.inflate(R.layout.fragment_bookmovie2, container, false);
progress = (LinearLayout) ll.findViewById(R.id.progress_bookingFrag);
recyclerView = (RecyclerView) ll.findViewById(R.id.recycle_movielist);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new Movie_listAdapter2(getActivity(),moviename,movieyear,moviebanner);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return ll;
}
#Override
public void onClick(View view) {
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
/*#Override
public void onButtonClickListnerProceed(Integer pos) {
Intent booking_screen_redirect = new Intent(getActivity(), BookingScreen2.class);
booking_screen_redirect.putExtra("movie_name",moviename.get(pos));
this.onPause();
startActivity(booking_screen_redirect);
getActivity().overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}*/
}
Movie_listAdapter2.java
public class Movie_listAdapter2 extends RecyclerView.Adapter<Movie_listAdapter2.Movie_cards>{
final static String TAG="Movie_listAdapter2";
Context context_external;
ArrayList<String> moviename=new ArrayList<>();
ArrayList<String> movieyear=new ArrayList<>();
ArrayList<String> banner=new ArrayList<>();
public Movie_listAdapter2(Context context,ArrayList<String> resource, ArrayList<String> resource1, ArrayList<String> resource2) {
//set the context and the format of the layout inside the list item
//i.e R.layout.movie_list_adapter
//also the resource i.e the item names in an ArrayList
this.moviename = resource;
this.movieyear = resource1;
this.banner = resource2;
this.context_external=context;
Log.e(TAG,"size = "+movieyear.size()+" "+moviename.size());
}
public static class Movie_cards extends RecyclerView.ViewHolder {
CardView cv;
TextView movie_name;
TextView movie_year;
Button proceed;
ImageView movie_banner;
public Movie_cards(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.movie_list_card);
movie_name = (TextView)itemView.findViewById(R.id.tv_card_moviename);
movie_year = (TextView)itemView.findViewById(R.id.tv_card_movieyear);
movie_banner = (ImageView)itemView.findViewById(R.id.card_moviebanner);
proceed = (Button) itemView.findViewById(R.id.b_card_proceed);
}
}
#Override
public Movie_cards onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_card, parent, false);
Movie_cards pvh = new Movie_cards(v);
return pvh;
}
public void updateData(ArrayList<String> resource, ArrayList<String> resource1, ArrayList<String> resource2) {
this.moviename = resource;
this.movieyear = resource1;
this.banner = resource2;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(final Movie_cards holder, final int position) {
holder.movie_name.setText(moviename.get(position));
holder.movie_year.setText(movieyear.get(position));
Picasso.with(context_external)
.load(banner.get(position))
.placeholder(R.drawable.placeholder)
.networkPolicy(NetworkPolicy.OFFLINE)
.error(R.drawable.placeholder)
.fit()
.into(holder.movie_banner, new Callback() {
#Override
public void onSuccess() {
//i.e image was loaded from cache
}
#Override
public void onError() {
//image was downloaded as it wasn't available in cache
Picasso.with(context_external)
.load(banner.get(position))
.placeholder(R.drawable.placeholder)
.error(R.drawable.warning)
.fit()
.into(holder.movie_banner);
}
});
holder.proceed.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent booking_screen_redirect = new Intent(context_external, BookingScreen2.class);
booking_screen_redirect.putExtra("movie_name",moviename.get(position));
context_external.startActivity(booking_screen_redirect);
//overridePendingTransition(R.anim.pull_in_right, R.anim.push_out_left);
}
});
}
#Override
public int getItemCount() {
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
the fragment displays empty and no items appear even though i have added the data to arraylists and passed to the adapter. please help . thanks in advance
Problem is in below code you are returning 0 that's why its not showing any item
#Override
public int getItemCount() {
return 0;
}
You should return your list's size here either moviename.size(); or movieyear.size()
I have an adapter which won't get notified after fetching new data by Retrofit however, I'm using notifyDataSetChanged and get success in the logs but nothing works either :(
Also I tried to use local array with this adapter and it works great.
public class alberrClassNews extends Fragment {
private RecyclerView recyclerView;
private List<alberrNewsListContent> alberrNews = new ArrayList<alberrNewsListContent>();
private final String TAG = "Get JSONArray";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.alberrnewsclass, container, false);
getActivity().setTitle("nnnn");
recyclerView = (RecyclerView) view.findViewById(R.id.alberrNewsList);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
final alberrNewsAdapter aNA = new alberrNewsAdapter(getActivity(), alberrNews);
recyclerView.setAdapter(aNA);
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("loading");
progressDialog.show();
final Retrofit alberrRetrofit = new Retrofit.Builder()
.baseUrl("http://nn.com/abbn/")
.addConverterFactory(GsonConverterFactory.create()).build();
alberrService service = alberrRetrofit.create(alberrService.class);
Call<JSONArray> call = service.alberrNews();
call.enqueue(new Callback<JSONArray>() {
#Override
public void onResponse(Call<JSONArray> call, Response<JSONArray> response) {
progressDialog.dismiss();
Log.i(TAG, "success");
try{
JSONArray jsonArray = response.body().getJSONArray(0);
for (int i = 0 ; i < jsonArray.length() ; i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
alberrNewsListContent newsContent = new alberrNewsListContent();
newsContent.setAlberrNewsTitle(jsonObject.getString("title"));
newsContent.setAlberrNewsSubject(jsonObject.getString("subject"));
newsContent.setAlberrNewsImage(jsonObject.getString("image"));
alberrNews.add(newsContent);
}
} catch (JSONException e){
e.printStackTrace();
}
aNA.notifyDataSetChanged();
}
#Override
public void onFailure(Call<JSONArray> call, Throwable t) {
Log.i(TAG, "Failed");
progressDialog.dismiss();
Toast.makeText(getActivity().getApplicationContext(),
"no connection", Toast.LENGTH_SHORT).show();
}
});
return view;
}
Adapter Class
public class alberrNewsAdapter extends RecyclerView.Adapter<alberrNewsAdapter.ViewHolder> {
private List<alberrNewsListContent> newsListContent;
private Context context;
public alberrNewsAdapter(Context ncontext , List<alberrNewsListContent> nnewsListContent ){
this.context = ncontext;
this.newsListContent = nnewsListContent;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.alberrnewscontent, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(alberrNewsAdapter.ViewHolder holder, int position) {
final alberrNewsListContent newsContent = newsListContent.get(position);
holder.alberrNewsTitle.setText(newsContent.getAlberrNewsTitle());
holder.alberrNewsSubject.setText(newsContent.getAlberrNewsSubject());
Glide.with(context)
.load(newsContent.getAlberrNewsImage())
.override(300, 260)
.into(holder.alberrNewsImage);
}
#Override
public int getItemCount() {
return newsListContent.size();
}
public void replaceDataSet(List<alberrNewsListContent> alberrNews){
this.newsListContent = alberrNews;
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView alberrNewsTitle;
TextView alberrNewsSubject;
ImageView alberrNewsImage;
CardView alberrNewsCardView;
public ViewHolder(View itemView) {
super(itemView);
alberrNewsTitle = (TextView)itemView.findViewById(R.id.alberrNewsTitle);
alberrNewsSubject = (TextView)itemView.findViewById(R.id.alberrNewsSubject);
alberrNewsImage = (ImageView)itemView.findViewById(R.id.alberrNewsImage);
alberrNewsCardView = (CardView)itemView.findViewById(R.id.alberrNewsCardView);
}
}
}
In your alberrNewsAdapter, you can create a new method called replaceDataSet() which will replace your dataset in the adapter and call notifyDataSetChanged().
private List<alberrNewsListContent> alberrNews alberrNews;
public void replaceDataSet(List<alberrNewsListContent> alberrNews){
this.alberrNews = alberrNews;
notifyDataSetChanged();
}
And in onResponse() instead of calling aNA.notifyDataSetChanged(); call aNA.replaceDataSet();
Pass new list content to the adapter via public method and call notifyDataSetChanged(); inside that method. Currently, you're not updating the list inside the adapter.