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();
Related
I'm creating a simple note app in which I'm showing the content in recycler view from firestore. Something is wrong in the code its not displaying the content in the recylerview(though I'm getting a new item each time I add a new note). Also it not updated as soon as I add a new note, its updated once I destroy the app.
Main activity
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
CustomAdapter customAdapter;
ArrayList<Model> models;
FirebaseFirestore firebaseFirestore;
FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
models = new ArrayList<>();
firebaseFirestore = FirebaseFirestore.getInstance();
customAdapter = new CustomAdapter(this, models);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(customAdapter);
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseFirestore.collection("my_notes_collection").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if(!queryDocumentSnapshots.isEmpty()){
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for(DocumentSnapshot d : list){
Model model = d.toObject(Model.class);
models.add(model);
}
customAdapter.notifyDataSetChanged();
}
else
Toast.makeText(getApplicationContext(), "No data", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Fail to get the data.", Toast.LENGTH_SHORT).show();
}
});
fab = findViewById(R.id.fab);
fab.setOnClickListener(view -> addData());
}
private void addData() {
Intent intent = new Intent(this, DataAdd.class);
startActivity(intent);
}
}
CustomAdapter
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder>{
Context context;
ArrayList<Model> models;
public CustomAdapter(Context context, ArrayList<Model> models){
this.context = context;
this.models = models;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.list_content, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.time_text.setText(models.get(holder.getBindingAdapterPosition()).getText());
holder.string_text.setText(models.get(holder.getBindingAdapterPosition()).getNotes());
holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context.getApplicationContext(), NotesDetails.class);
intent.putExtra("position", String.valueOf(holder.getBindingAdapterPosition()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() { return models.size(); }
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView string_text, time_text;
ConstraintLayout constraintLayout;
public MyViewHolder(View itemView) {
super(itemView);
string_text = itemView.findViewById(R.id.textView);
time_text = itemView.findViewById(R.id.timeshow);
constraintLayout = itemView.findViewById(R.id.constraintLayout);
}
}
}
By looks of it, the reason its not updating RV is because we are not asking the code to do that, yet.
So listen for when DataAdd activity has completed its addition task by using startActivityForResult() please see an example here
Then when we know add was successful, we get a callback in, onActivityResult() we then reload list from Firebase
firebaseFirestore.collection("my_notes_collection").get()
...
again such that the list is updated and dataset is notified..
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);
This is My Code:
public class ItemsListActivity extends AppCompatActivity {
private List<AllItems> listItems;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_items_list);
Button camera=(Button)findViewById(R.id.camera);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(ItemsListActivity.this, Camera.class);
startActivity(i);
}
});
getData();
}
private void getData(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
loading.dismiss();
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
AllItems items = new AllItems();
JSONObject json = null;
try {
json = array.getJSONObject(i);
items.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
items.setName(json.getString(Config.TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
listItems.add(items);
}
adapter = new CardAdapter(listItems, this);
recyclerView.setAdapter(adapter);
adapter.notifyItemRangeChanged(0, listItems.size());
}
}
And This Is CardAdapter:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
private ImageLoader imageLoader;
private Context context;
List<AllItems> superHeroes;
public CardAdapter(List<AllItems> superHeroes, Context context){
super();
this.superHeroes = superHeroes;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.all_items_lists, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
AllItems superHero = superHeroes.get(position);
imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.mipmap.ic_launcher, android.R.drawable.ic_dialog_alert));
holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
holder.textViewName.setText(superHero.getName());
}
#Override
public int getItemCount() {
return superHeroes.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public NetworkImageView imageView;
public TextView textViewName;
public ViewHolder(View itemView) {
super(itemView);
imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
}
}
}
how do I update adapter data in order to display newly received items?
You are creating instance of adapter every time you parsing the data,
just create its instance once in onCreate() method like below:
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
adapter = new CardAdapter(listItems, this);
recyclerView.setAdapter(adapter);
and just notify the adapter with your parse data like below:
listItems.add(items);
adapter.notifyDataSetChanged();
will work for you.
Here what is happening that evertime your are calling getData() you are initializing adapter again . Instead you should initialize your adapter in onCreate and in getData just update the list that you are passing in adapter and call adapter.notifyDataSetChanged().
private List<AllItems> listItems;
private RecyclerView recyclerView; private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter; #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_items_list); Button camera=(Button)findViewById(R.id.camera); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); listItems = new ArrayList<>();
adapter = new CardAdapter(listItems, this);
recyclerView.setAdapter(adapter);
camera.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View view) { Intent i = new Intent(ItemsListActivity.this, Camera.class); startActivity(i); } }); getData(); }
private void getData(){
final ProgressDialog loading = ProgressDialog.show(this,"Loading Data", "Please wait...",false,false);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL, new Response.Listener<JSONArray>() { #Override public void onResponse(JSONArray response) { loading.dismiss(); parseData(response); }
}, new Response.ErrorListener() {
#Override public void onErrorResponse(VolleyError error) { } }); RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(jsonArrayRequest); }
private void parseData(JSONArray array){
for(int i = 0; i<array.length(); i++) {
AllItems items = new AllItems(); JSONObject json = null;
try
{
json = array.getJSONObject(i); items.setImageUrl(json.getString(Config.TAG_IMAGE_URL)); items.setName(json.getString(Config.TAG_NAME)); } catch (JSONException e) { e.printStackTrace(); } listItems.add(items); }
}
adapter.notifyDataSetChanged().
}
And if you don't want to show previous items call lisItems.clear() before adding new items
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 Android Activity that have a RecycleView. I want to add an event listener, so I have build this code:
public class ResultActivity extends AppCompatActivity {
private List<Result> lista;
private RecyclerView recyclerView;
private ResultsAdapter pAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results_activity);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
//recupero la lista delle medication
ResultDAO manager = new ResultDAO(this);
lista=manager.getResults();
pAdapter = new ResultsAdapter(lista, new ResultsAdapter.OnItemClickListener() {
#Override
public void onItemClick(Result item) {
try{
//recupero i dati della lista in pagina
final Dialog dialog = new Dialog(ResultActivity.this);
//setting custom layout to dialog
dialog.setContentView(R.layout.result_modal);
dialog.setTitle("Parametri");
}catch(Exception e){
Log.e("","");
}
}
});
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(pAdapter);
}
}
This is my custom adapter:
public class ResultsAdapter extends RecyclerView.Adapter<ResultsAdapter.MyViewHolder> {
private List<Result> list;
private final OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(Result item);
}
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView startDate, endDate,examination;
Result result;
public MyViewHolder(View view) {
super(view);
startDate = (TextView) view.findViewById(R.id.startDate);
endDate = (TextView) view.findViewById(R.id.endDate);
examination = (TextView) view.findViewById(R.id.examination);
}
}
public ResultsAdapter(List<Result> list,OnItemClickListener listener)
{
this.listener=listener;
this.list = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.results_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Result result = list.get(position);
holder.startDate.setText(result.getDateStart()!=null ? result.getDateStart() : "");
holder.endDate.setText(result.getDateEnd()!=null ? result.getDateEnd() : "");
holder.examination.setText(result.getInfo().getDisplayName());
}
#Override
public int getItemCount() {
return list.size();
}
}
Now if I try to start my application and I try to click on one or more item, the method OnClick, does not start.
How can I fixed it?
Read this answer for better understanding
Use below code in Adapter class :-
holher.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// your code
}
});
Check this blog post.
http://www.littlerobots.nl/blog/Handle-Android-RecyclerView-Clicks/
It allows you to add 'on-click-listeners' in a much simpler, reusable way.
Example:
ItemClickSupport.addTo(recyclerView).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
#Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
// Do your thing
}
});