I've been trying to get Onclik events on RecyclerView to display the same data that the RecyclerView had in a new activity with even more data that wasn't previously there. Right now I have data like name, phone number but I would like to add morelike website... So far the code I tried is crashing when i click on the View. I don't know what is wrong. can anyone help ?
Here's my main fragment
public class Entreprisesfrag extends android.support.v4.app.Fragment {
RecyclerView recyclerView;
DatabaseReference dbref;
FirebaseDatabase firebaseDatabase;
LinearLayout linearLayout;
LinearLayoutManager linearLayoutManager;
public Entreprisesfrag() {
// Required empty public constructor
}
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_entreprises, container,
false);
recyclerView= view.findViewById(R.id.recv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager (new LinearLayoutManager(getContext()));
linearLayout= view.findViewById(R.id.entreprise_list_layout);
firebaseDatabase= FirebaseDatabase.getInstance();
dbref= firebaseDatabase.getReference("Entreprises");
return view;
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<entreprises_class,ViewHolder>firebaseRecyclerAdapter=
new FirebaseRecyclerAdapter<entreprises_class, ViewHolder>
(entreprises_class.class,R.layout.entreprises_list,
ViewHolder.class,dbref.orderByChild("nom")) {
#Override
protected void populateViewHolder(ViewHolder viewHolder,
entreprises_class model, int position) {
viewHolder.details(getActivity(), model.getNom(),model.getNum(),
model.getSecteur(), model.getSpécialité(), model.getVille(),
model.getImage());
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
ViewHolder viewHolder = super.onCreateViewHolder(parent,
viewType);
viewHolder.setOnClickListener(new ViewHolder.ClickListener() {
#Override
public void onItemClick(View view, int position) {
TextView textView=
view.findViewById(R.id.entreprise_nom);
TextView textView1=
view.findViewById(R.id.entreprise_secteur);
TextView textView2=
view.findViewById(R.id.entreprise_sous_secteur);
TextView textView3=
view.findViewById(R.id.entreprise_ville);
TextView textView4=
view.findViewById(R.id.entreprise_num);
ImageView
imageView=view.findViewById(R.id.entreprise_image);
String snom= textView.getText().toString();
String ssec= textView1.getText().toString();
String ssp= textView2.getText().toString();
String sv= textView3.getText().toString();
String snum= textView4.getText().toString();
Drawable drawable= imageView.getDrawable();
Bitmap bitmap=((BitmapDrawable)drawable).getBitmap();
Intent i= new Intent(view.getContext(),
entProfileFull.class);
ByteArrayOutputStream byteArrayOutputStream= new
ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100,
byteArrayOutputStream);
byte[] bytes= byteArrayOutputStream.toByteArray();
i.putExtra("image", bytes);
i.putExtra("nom", snom);
i.putExtra("secteur", ssec);
i.putExtra("spécialité", ssp);
i.putExtra("ville", sv);
i.putExtra("num", snum);
startActivity(i);
}
#Override
public void onItemLongClick(View view, int position) {
}
});
return viewHolder;
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
public void recherche(String texte){
Query mQuery= dbref.orderByChild("spécialité");
FirebaseRecyclerAdapter<entreprises_class,ViewHolder>firebaseRecyclerAdapter=
new FirebaseRecyclerAdapter<entreprises_class, ViewHolder>
(entreprises_class.class,R.layout.entreprises_list,
ViewHolder.class,mQuery) {
#Override
protected void populateViewHolder(ViewHolder viewHolder,
entreprises_class model, int position) {
viewHolder.details(getActivity(), model.getNom(),model.getNum(),
model.getSecteur(), model.getSpécialité(), model.getVille(),
model.getImage());
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
ViewHolder viewHolder = super.onCreateViewHolder(parent,
viewType);
viewHolder.setOnClickListener(new ViewHolder.ClickListener() {
#Override
public void onItemClick(View view, int position) {
TextView textView=
view.findViewById(R.id.entreprise_nom);
TextView textView1=
view.findViewById(R.id.entreprise_secteur);
TextView textView2=
view.findViewById(R.id.entreprise_sous_secteur);
TextView textView3=
view.findViewById(R.id.entreprise_ville);
TextView textView4=
view.findViewById(R.id.entreprise_num);
ImageView
imageView=view.findViewById(R.id.entreprise_image);
String snom= textView.getText().toString();
String ssec= textView1.getText().toString();
String ssp= textView2.getText().toString();
String sv= textView3.getText().toString();
String snum= textView4.getText().toString();
Drawable drawable= imageView.getDrawable();
Bitmap bitmap=((BitmapDrawable)drawable).getBitmap();
Intent i= new Intent(view.getContext(),
entProfileFull.class);
ByteArrayOutputStream byteArrayOutputStream= new
ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100,
byteArrayOutputStream);
byte[] bytes= byteArrayOutputStream.toByteArray();
i.putExtra("image", bytes);
i.putExtra("nom", snom);
i.putExtra("secteur", ssec);
i.putExtra("spécialité", ssp);
i.putExtra("ville", sv);
i.putExtra("num", snum);
startActivity(i);
}
#Override
public void onItemLongClick(View view, int position) {
}
});
return viewHolder;
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.recherche_activity_menu_item, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) item.getActionView();
searchView.setQueryHint("Nom, Spécialité ou Ville");
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
recherche(query);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
recherche(newText);
return false;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.recherche)
{
}
else if (item.getItemId()==R.id.filtrer)
{
FiltreDialog();
}
return super.onOptionsItemSelected(item);
}
private void FiltreDialog() {
String [] Options={"Spécialité", "Ville"};
AlertDialog.Builder builder= new AlertDialog.Builder(getContext());
builder.setTitle("Afficher par:")
.setIcon(R.drawable.ic_sort_black_24dp)
.setItems(Options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(which==0){
FirebaseRecyclerAdapter<entreprises_class,ViewHolder>firebaseRecyclerAdapter=
new FirebaseRecyclerAdapter<entreprises_class, ViewHolder>
(entreprises_class.class,R.layout.entreprises_list,
ViewHolder.class,dbref.orderByChild("spécialité")) {
#Override
protected void populateViewHolder(ViewHolder
viewHolder, entreprises_class model, int position) {
viewHolder.details(getActivity(),
model.getNom(),model.getNum(), model.getSecteur(), model.getSpécialité(),
model.getVille(), model.getImage());
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
else if(which==1){
FirebaseRecyclerAdapter<entreprises_class,ViewHolder>firebaseRecyclerAdapter=
new FirebaseRecyclerAdapter<entreprises_class, ViewHolder>
(entreprises_class.class,R.layout.entreprises_list,
ViewHolder.class,dbref.orderByChild("ville")) {
#Override
protected void populateViewHolder(ViewHolder
viewHolder, entreprises_class model, int position) {
viewHolder.details(getActivity(),
model.getNom(),model.getNum(), model.getSecteur(), model.getSpécialité(),
model.getVille(), model.getImage());
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
}
});
builder.show();
}
}
Over Here is my new Activity
public class entProfileFull extends AppCompatActivity {
Toolbar mtoolbar;
TextView textView, textView1, textView2, textView3, textView4;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ent_profile_full);
mtoolbar=findViewById(R.id.toolbar);
setSupportActionBar(mtoolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
textView=findViewById(R.id.nom_entreprise_full);
textView1=findViewById(R.id.secteur_entreprise_full);
textView2= findViewById(R.id.sp_entreprise_full);
textView3=findViewById(R.id.entreprise_ville);
textView4=findViewById(R.id.entreprise_num_full);
imageView=findViewById(R.id.entreprise_image_full);
byte[] bytes=getIntent().getByteArrayExtra("image");
String nom= getIntent().getStringExtra("nom");
String secteur= getIntent().getStringExtra("secteur");
String spécialité= getIntent().getStringExtra("spécialité");
String ville= getIntent().getStringExtra("ville");
String num= getIntent().getStringExtra("num");
Bitmap bm= BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
textView.setText(nom);
textView1.setText(secteur);
textView2.setText(spécialité);
textView3.setText(ville);
textView4.setText(num);
imageView.setImageBitmap(bm);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is my ViewHolder Class
public class ViewHolder extends RecyclerView.ViewHolder {
View mView;
public ViewHolder(View itemView) {
super(itemView);
mView=itemView;
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
vclickListener.onItemClick(view, getAdapterPosition());
}
});
itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
vclickListener.onItemLongClick(view, getAdapterPosition());
return true;
}
});
}
public void details(Context cntx, String nom, String num, String secteur,
String spécialité,String ville, String image){
TextView textView= mView.findViewById(R.id.entreprise_nom);
TextView textView1= mView.findViewById(R.id.entreprise_secteur);
TextView textView2= mView.findViewById(R.id.entreprise_sous_secteur);
TextView textView3= mView.findViewById(R.id.entreprise_ville);
TextView textView4= mView.findViewById(R.id.entreprise_num);
ImageView imageView= mView.findViewById(R.id.entreprise_image);
textView.setText(nom);
textView1.setText(secteur);
textView2.setText(spécialité);
textView3.setText(ville);
textView4.setText(num);
Picasso.get().load(image).into(imageView);
}
private ViewHolder.ClickListener vclickListener;
public interface ClickListener{
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
public void setOnClickListener(ViewHolder.ClickListener clickListener){
vclickListener = clickListener;
}
}
You shouldn't be calling itemView.setOnClickListener() from ViewHolder constructor. Because ViewHolder constructor is called from the onCreateViewHolder method. Henc you'll not have the position. So keep the itemView.setOnClickListener() methods inside onBindView() method
This will fix the issue
Related
I'm not very good in android programming. I'm able to do this layout with cardview and recyclerview.
But I need to have a 2 listener for each card with editText. An OnFocusChange listener and a OnTextChange listener. And I have to get the text of each editText.
What have I to done?
This is my current code:
Object:
public class unitObject {
private String mtitle;
private String mhint;
unitObject(String title, String hint){
mtitle=title;
mhint=hint;
}
public String getMtitle() {
return mtitle;
}
public String getMhint() {
return mhint;
}
public void setMtitle(String mtitle) {
this.mtitle = mtitle;
}
public void setMhint(String mhint) {
this.mhint = mhint;
}
}
Recycler adapter:
public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.DataObjectHolder> {
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<unitObject> mDataset;
private static MyClickListener myClickListener;
public static class DataObjectHolder extends RecyclerView.ViewHolder
implements View
.OnClickListener {
TextView title;
TextView ET_hint;
String content;
public DataObjectHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textView);
ET_hint = (TextView) itemView.findViewById(R.id.editText);
Log.i(LOG_TAG, "Adding Listener");
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
myClickListener.onItemClick(getAdapterPosition(), v);
}
}
public MyRecyclerViewAdapter(ArrayList<unitObject> myDataset) {
mDataset = myDataset;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view_row, parent, false);
DataObjectHolder dataObjectHolder = new DataObjectHolder(view);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(DataObjectHolder holder, int position) {
holder.title.setText(mDataset.get(position).getMtitle());
holder.ET_hint.setHint(mDataset.get(position).getMhint());
}
#Override
public int getItemCount() {
return mDataset.size();
}
public interface MyClickListener {
public void onItemClick(int position, View v);
}
The class
public class classic_conversion extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.classic_conversion_layout);
mRecyclerView = findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyRecyclerViewAdapter(getDataSet());
mRecyclerView.setAdapter(mAdapter);
}
private ArrayList<unitObject> getDataSet() {
ArrayList results = new ArrayList<unitObject>();
results.add(new unitObject("Title 1","hint 1"));
results.add(new unitObject("Title 2","hint 2"));
results.add(new unitObject("Title 3","hint 3"));
return results;
}
}
Thanks in advance!
For listener editText:
yourEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//BEFORE TEXT CHANGED
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// WHILE TEXT IS CHANGE
}
#Override
public void afterTextChanged(Editable editable) {
//AFTER TEXT CHANGED (LIKE YOU PRESS ENTER AFTER TYPING)
}
});
For listener focus change.
yourEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus){
//DO WHAT YOU NEED WHEN editText HAS FOCUS
}
else {
//DO WHAT YOU NEED WHEN editText HAS NO FOCUS
}
}
});
I really hope this helps you, and sorry for the late reply.
I am developing an android app. for that I have created table product
with columns title, Image1,Image2 , etc
I want to display it in a recycler view or card view. including images. how can i do that...?
public class Productfragment extends Fragment {
private static BUser user = (BUser) ParseUser.getCurrentUser();
private enter code here
static BStore store = user.getCurrentStore();
List<BProduct> pets = new ArrayList<BProduct>();
public String [] ii;
public Productfragment(){
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView recyclerView = (RecyclerView) inflater.inflate(
R.layout.recycler_view, container, false);
ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return recyclerView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.search_menu, menu);
//super.onCreateOptionsMenu(menu, inflater);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public SimpleDraweeView picture;
public TextView name;
public TextView description;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.productfragment, parent, false));
picture = (SimpleDraweeView) itemView.findViewById(R.id.card_image);
name = (TextView) itemView.findViewById(R.id.card_title);
// Adding Snackbar to Action Button inside card
Button button = (Button)itemView.findViewById(R.id.action_button);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Snackbar.make(v, "Action is pressed",
Snackbar.LENGTH_LONG).show();
}
});
ImageButton favoriteImageButton =
(ImageButton) itemView.findViewById(R.id.favorite_button);
favoriteImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Snackbar.make(v, "Added to Favorite",
Snackbar.LENGTH_LONG).show();
}
});
ImageButton shareImageButton = (ImageButton) itemView.findViewById(R.id.share_button);
shareImageButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Snackbar.make(v, "Share article",
Snackbar.LENGTH_LONG).show();
}
});
}
}
/**
* Adapter to display recycler view.
*/
public class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
// Set numbers of Card in RecyclerView.
private static final int LENGTH = 4;
String [] mylist ;
public ContentAdapter(Context context) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Product");
// query.whereEqualTo("storeI", store.getObjectId());
query.findInBackground(new FindCallback<ParseObject>() {
// ArrayList<ParseFile>myImage = new ArrayList<ParseFile>();
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
for (int i=0; i<scoreList.size(); ++i) {
mylist[i] = scoreList.get(i).getString("description");
// mylist.add(name);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//holder.picture.setImageURI(mPlacePictures[position % mPlacePictures.length]);
holder.name.setText(mylist[position]);
}
#Override
public int getItemCount() {
return LENGTH;
}
}
}
i develop app using firebase to upload files and view it in Recyclerview
when i click on any item should take me to another activity and view the file in webView the issue is when i click on any item take the first file uploaded to firebase , i need when i click in any item take the file for this item
public class postShows extends AppCompatActivity {
private RecyclerView postlist;
private DatabaseReference mdatabase;
private FirebaseAuth auth;
ImageView imagepostl;
TextView textname;
String ma,mmmmmm;
PostUtils m;
Context context;
public static String imageURL, fileType,fileNAme;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_shows);
mdatabase = FirebaseDatabase.getInstance().getReference().child(PostNew.item);
auth = FirebaseAuth.getInstance();
imagepostl = (ImageView) findViewById(R.id.imagefilesource);
textname = (TextView) findViewById(R.id.textfilename);
postlist = (RecyclerView) findViewById(R.id.postRecycle);
postlist.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
postlist.setLayoutManager(linearLayoutManager);
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<PostUtils, PostViewHolder> firebaseRecyclerAdapter = new
FirebaseRecyclerAdapter<PostUtils, PostViewHolder>(
PostUtils.class,
R.layout.post_row,
PostViewHolder.class,
mdatabase
)
{
#Override
protected void populateViewHolder(PostViewHolder viewHolder, PostUtils m, int position) {
fileType = m.getfiletype();
fileNAme=m.getFileName();
// viewHolder.setDesc(m.getDescription());
if (m.getfiletype().equals("application/vnd.openxmlformats-officedocument.wordprocessingml.document")) {
// imagepostl.setImageResource(R.drawable.word);
viewHolder.setFileName(m.getFileName());
viewHolder.setWord(imagepostl);
mmmmmm= viewHolder.setImageURL(ma,m);
} else if (m.getfiletype().equals("application/pdf")) {
viewHolder.setFileName(m.getFileName());
viewHolder.setPDF(imagepostl);
mmmmmm= viewHolder.setImageURL(ma,m);
} else if (m.getfiletype().contains("image")) {
viewHolder.setimage(imagepostl);
mmmmmm= viewHolder.setImageURL(ma,m);
} else {
viewHolder.setFileName(m.getFileName());
{
viewHolder.setimage(imagepostl);
}
}
}
#Override
public PostViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
PostViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
viewHolder.setOnClickListener(new PostViewHolder.ClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(Kasittestbank.getAppContext(), Kasit.class);
intent.putExtra("imageURL",mmmmmm);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Kasittestbank.getAppContext().startActivity(intent);
}
#Override
public void onItemLongClick(View view, int position) {
Toast.makeText(Kasittestbank.getAppContext(), "Item long clicked at " + position, Toast.LENGTH_SHORT).show();
}
});
return viewHolder;
}
};
postlist.setAdapter(firebaseRecyclerAdapter);
}
public static class PostViewHolder extends RecyclerView.ViewHolder {
View mview;
Bitmap bitmap;
FileOpen fileOpen;
public PostViewHolder(View itemView) {
super(itemView);
mview = itemView;
mview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mClickListener.onItemClick(v, getAdapterPosition());
}
});
}
private PostViewHolder.ClickListener mClickListener;
//Interface to send callbacks...
public interface ClickListener {
public void onItemClick(View view, int position);
public void onItemLongClick(View view, int position);
}
public void setOnClickListener(PostViewHolder.ClickListener clickListener) {
mClickListener = clickListener;
}
public void setFileName(String name) {
TextView textName = (TextView) mview.findViewById(R.id.textfilename);
textName.setText(name);
}
public void setWord(ImageView imageResourses) {
ImageView imageView = (ImageView) mview.findViewById(R.id.imagefilesource);
imageView.setImageResource(R.drawable.word);
}
public void setPDF(ImageView imageResourses) {
ImageView imageView = (ImageView) mview.findViewById(R.id.imagefilesource);
imageView.setImageResource(R.drawable.pdf);
}
public void setimage(ImageView imageResourses) {
ImageView imageView = (ImageView) mview.findViewById(R.id.imagefilesource);
imageView.setImageResource(R.drawable.image);
}
public String setImageURL(String url, PostUtils maa){
url=maa.getImageUrl();
return url;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logut:
Logut();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
return super.onOptionsItemSelected(item);
}
public void Logut() {
auth.signOut();
finish();
}
}
When you define a recyclerView, one method you should override is onBindViewHolder. Inside of that method is where you define the content of each element of the recyclerView.
So if you want to each row can be clickable, think you need something like this:
#Override
public void onBindViewHolder(PostViewHolder postViewHolder, int i) {
postViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Definde what happend when the item is clicked
//To identify which row, you can use postViewHolder.getAdapterPosition();
}
});
}
Let me know if works.
I have a VerticalGridView that is using a RecyclerView.Adapter to populate the elements. I have discovered that the onBindViewHolder() method does not get called if the potential element is off of the viewport. Unfortunately, this is causing a NullPointerException from a different method because I am catching a TextView reference in the onBindViewHolder() method and passing it to an outside variable for later manipulation.
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.txtCategoryName.setText(categories.get(position).getStrCategory());
categories.get(position).setTxtViewReference(viewHolder.txtCategoryDefectTotal);
viewHolder.categoryBoxRoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(CategoryListItem catItem : categories){
if(catItem.getStrCategory().equals(viewHolder.txtCategoryName.getText())){
int index = Defects.getInstance().getCategories().indexOf(catItem) + 1;
MainInterface.grids.get(index).bringToFront();
MainInterface.grids.get(index).setVisibility(View.VISIBLE);
for(VerticalGridView grid : MainInterface.grids){
int gridIndex = MainInterface.grids.indexOf(grid);
if(gridIndex != index){
grid.setVisibility(View.INVISIBLE);
}
}
break;
}
}
}
});
From what I understand, the reference to the TextView gets created when the Viewholder object is instantiated.
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtCategoryName;
public TextView txtCategoryDefectTotal;
public View categoryBoxRoot;
public ViewHolder(View itemView) {
super(itemView);
txtCategoryName = (TextView) itemView.findViewById(R.id.textViewCategoryName);
txtCategoryDefectTotal = (TextView) itemView.findViewById(R.id.textViewCategoryTotalDefects);
categoryBoxRoot = itemView.findViewById(R.id.root_category_box);
}
}
Is there a way to force onBindViewHolder() to be called on all elements at least one time when the Adapter is instantiated?
I attempted the suggestions here without any success.
I understand that forcing onBindViewHolder() on all elements would work against the whole purpose of the RecycleView.Adapter. Thus, I am open to any other suggestions on how I can catch that TextView reference.
As a temporary fix to this problem, I am able to use a try catch block around the method that generates the NullPointerException. However, I am concerned that the lack of the reference means I could introduce errors in the future.
The easiest solution for this problem is to scroll down to the bottom of the grid and then back up to the top. This cannot be done in the onCreate() method though because the grid is not technically visible at that time. Instead, it should be called in the onResume() method of the activity.
#Override
public void onResume(){
super.onResume();
VerticalGridView defectGrid = grids.get(0);
RecyclerView.Adapter adapter = defectGrid.getAdapter();
defectGrid.smoothScrollToPosition(adapter.getItemCount()-1);
defectGrid.smoothScrollToPosition(0);
}
This was a good attempt at a solution but unfortunately it still does not work. While it does get the reference to make the method work, it does NOT necessarily have the right reference. I found that the reference can end up pointing at a different TextView as the RecycleView.Adapter reuses views to display them in different areas.
SOLUTION:
Mark Keen was right when he said to use notifyDataSetChanged(). I got it to work by fixing my onBindViewHolder() method to work properly.
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.txtCategoryName.setText(categories.get(position).getStrCategory());
viewHolder.txtCategoryDefectTotal.setText(String.valueOf(categories.get(position).getTotalDefectsInCategory()));
}
I also changed my data object so it holds an int value instead of a reference to the TextView since the above proved that reference was invalid. Finally, I added a call to my Adapter when I pressed my custom back button.
grids.get(0).getAdapter().notifyDataSetChanged();
Thank you everyone who contributed!
Just reset the Adapter like this
RecyclerView.Adapter adapter = recList.getAdapter();
recList.setAdapter(null);
recList.setAdapter(adapter);
recList should be you RecyclerView.
wrap your RecyclerView in a NestedScrollView that will force all the items to be bound in advance.
<androidx.core.widget.NestedScrollView
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvGrid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false" />
</androidx.core.widget.NestedScrollView>
Understand Flow
public class ThemeGridAdapter extends RecyclerView.Adapter<ThemeGridAdapter.ViewHolder> {
private OnItemClickedListener listener;
private List<Theme> mDataset;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public TextView subtitle;
// public SimpleDraweeView image;
public ImageView img;
public ViewGroup container;
public ViewHolder(RelativeLayout v) {
super(v);
container = v;
title = (TextView) v.findViewById(R.id.theme_name_text);
subtitle = (TextView) v.findViewById(R.id.theme_name_type);
// image = (SimpleDraweeView) v.findViewById(R.id.cell_img);
img = (ImageView) v.findViewById(R.id.cell_img);
}
}
public ThemeGridAdapter(List<Theme> dataset) {
mDataset = dataset;
}
#Override
public ThemeGridAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RelativeLayout v = (RelativeLayout) LayoutInflater.from(parent.getContext())
.inflate(R.layout.cell, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.title.setText(mDataset.get(position).getTitle());
holder.subtitle.setText(mDataset.get(position).getAuthor());
// Uri uri = Uri.parse(mDataset.get(position).getUrl());
holder.img.setImageResource(mDataset.get(position).getImage());
// holder.image.setImageURI(uri);
holder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null)
listener.onItemClicked(holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return mDataset.size();
}
public void setListener(OnItemClickedListener listener) {
this.listener = listener;
}
}
Check the style of binding view
public class CrimeListFragment extends Fragment {
private static final String SAVED_SUBTITLE_VISIBLE = "subtitle";
private static final int REQUEST_CRIME = 1;
private RecyclerView mRecyclerView;
private CrimeAdapter mCrimeAdapter;
private boolean mSubtitleVisible;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.crime_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
if (savedInstanceState != null){
mSubtitleVisible = savedInstanceState.getBoolean(SAVED_SUBTITLE_VISIBLE);
}
updateUI();
return view;
}
private void updateUI() {
CrimeLab crimeLab = CrimeLab.get(getActivity());
List<Crime> crimes = crimeLab.getCrimes();
if (mCrimeAdapter == null) {
mCrimeAdapter = new CrimeAdapter(crimes);
mRecyclerView.setAdapter(mCrimeAdapter);
} else {
mCrimeAdapter.setCrimes(crimes);
mCrimeAdapter.notifyDataSetChanged();
}
updateSubtitle();
}
private class CrimeHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView mTitleTextView;
private TextView mDateTextView;
private CheckBox mSolvedCheckBox;
private Crime mCrime;
public CrimeHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mTitleTextView = (TextView) itemView.findViewById(R.id.list_item_crime_title_text_view);
mDateTextView = (TextView) itemView.findViewById(R.id.list_item_crime_date_text_view);
mSolvedCheckBox = (CheckBox) itemView.findViewById(R.id.list_item_crime_solved_checkbox);
}
public void bindCrime(Crime crime) {
mCrime = crime;
mTitleTextView.setText(mCrime.getTitile());
mDateTextView.setText(mCrime.getDate().toString());
mSolvedCheckBox.setChecked(mCrime.isSolved());
}
#Override
public void onClick(View v) {
/*Toast.makeText(getActivity(),mCrime.getTitile() + "clicked!", Toast.LENGTH_SHORT).show();*/
/*Intent for calling activity from fragment*/
/* Intent intent = new Intent(getActivity(), CrimeActivity.class);*/
/*Intent intent = CrimeActivity.newIntent(getActivity(),mCrime.getId());*/
Intent intent = CrimePagerActivity.newIntent(getActivity(), mCrime.getId());
/*startActivityForResult(intent,REQUEST_CRIME);*/
startActivity(intent);
}
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
private List<Crime> mCrimes;
public CrimeAdapter(List<Crime> crimes) {
mCrimes = crimes;
}
#Override
public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_item_crime, parent, false);
return new CrimeHolder(view);
}
#Override
public void onBindViewHolder(CrimeHolder holder, int position) {
Crime crime = mCrimes.get(position);
/*holder.mTextView.setText(crime.getTitile());*/
holder.bindCrime(crime);
}
#Override
public int getItemCount() {
return mCrimes.size();
}
public void setCrimes(List<Crime> crimes) {
mCrimes = crimes;
}
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CRIME) {
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_crime_list, menu);
MenuItem subtitleItem = menu.findItem(R.id.menu_item_show_subtitle);
if (mSubtitleVisible){
subtitleItem.setTitle(R.string.hide_subtitle);
}else {
subtitleItem.setTitle(R.string.show_subtitle);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_new_crime:
Crime crime = new Crime();
CrimeLab.get(getActivity()).addCrime(crime);
Intent intent = CrimePagerActivity.newIntent(getActivity(), crime.getId());
startActivity(intent);
return true;
case R.id.menu_item_show_subtitle:
mSubtitleVisible = !mSubtitleVisible;
getActivity().invalidateOptionsMenu();
updateSubtitle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void updateSubtitle(){
CrimeLab crimeLab = CrimeLab.get(getActivity());
int crimeCount = crimeLab.getCrimes().size();
String subtitle = getString(R.string.subtitle_format,crimeCount);
if (!mSubtitleVisible){
subtitle = null;
}
AppCompatActivity appCompatActivity = (AppCompatActivity)getActivity();
appCompatActivity.getSupportActionBar().setSubtitle(subtitle);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_SUBTITLE_VISIBLE,mSubtitleVisible);
}
}
I show list of data in card view successfully but now i want to open another activity and show details of clicked data.
I have three class MainActivity, ContactAdapter, Contact.
Main Activity Code:
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
String[] name,email;
ArrayList<Contact> list = new ArrayList<Contact>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
name = getResources().getStringArray(R.array.person_name);
email = getResources().getStringArray(R.array.person_email);
int count = 0;
for (String Name : name)
{
Contact contact = new Contact(Name,email[count]);
count++;
list.add(contact);
}
recyclerView= (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter=new ContactAdapter(list);
recyclerView.setAdapter(adapter);
i tried but it's not working.
Adapter Code:
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> {
ArrayList<Contact> contacts = new ArrayList<Contact>();
public ContactAdapter(ArrayList<Contact> contacts) {
this.contacts = contacts;
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_layout, parent, false);
ContactViewHolder contactViewHolder = new ContactViewHolder(view);
return contactViewHolder;
}
#Override
public void onBindViewHolder(ContactViewHolder holder, int position) {
Contact CON = contacts.get(position);
holder.person_name.setText(CON.getName());
holder.person_email.setText(CON.getEmail());
}
#Override
public int getItemCount() {
return contacts.size();
}
public static class ContactViewHolder extends RecyclerView.ViewHolder {
TextView person_name, person_email;
public ContactViewHolder(View view) {
super(view);
person_name = (TextView) view.findViewById(R.id.person_name);
person_email = (TextView) view.findViewById(R.id.person_email);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "OnClick Version :",
Toast.LENGTH_SHORT).show();
}
});
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(v.getContext(), "OnLongClick Version :",
Toast.LENGTH_SHORT).show();
return true;
}
});
}
}
}
In your adapter do this:
public class ProdutoAdapter extends RecyclerView.Adapter<ProdutoAdapter.ProdutoViewHolder>{
private static ProdutoAdapter.ClickListener clickListener; //this is important
private List<Produto> produtos; //this is my list of beans
public ProdutoAdapter(List<Produto> produtos) {
this.produtos = produtos;
}
#Override
public ProdutoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_produtos, parent, false);
ProdutoViewHolder mvh = new ProdutoViewHolder(v);
return mvh;
}
#Override
public void onBindViewHolder(ProdutoViewHolder holder, int position) {
//holder.nome.setText(this.produtos.get(position).getNome());
holder.img.setImageDrawable(produtos.get(position).getImgDrawable());
holder.nome.setText(produtos.get(position).getNome());
holder.preco.setText(String.valueOf(produtos.get(position).getPreco()));
}
#Override
public int getItemCount() {
return this.produtos.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class ProdutoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener{
Produto produto;
CardView cardView;
TextView nome;
TextView preco;
ImageView img;
ProdutoViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
cardView = (CardView) itemView.findViewById(R.id.cardviewProduto);
nome = (TextView) itemView.findViewById(R.id.nome);
preco = (TextView) itemView.findViewById(R.id.preco);
img = (ImageView) itemView.findViewById(R.id.foto);
}
public void setItem(Produto produto){
this.produto = produto;
}
public Produto getItem(){
return this.produto;
}
//this is what you'll need in your activity
#Override
public void onClick(View v) {
clickListener.onItemClick(getAdapterPosition(), v);
}
#Override
public boolean onLongClick(View v) {
clickListener.onItemLongClick(getAdapterPosition(), v);
return false;
}
}
public void setOnItemClickListener(ClickListener clickListener){
ProdutoAdapter.clickListener = clickListener;
}
public interface ClickListener {
void onItemClick(int position, View v);
void onItemLongClick(int position, View v);
}
}
and in your activity:
public static ProdutoAdapter mAdapter;
myActivity.mAdapter.setOnItemClickListener(new ProdutoAdapter.ClickListener() {
#Override
public void onItemClick(int position, View v) {
//do what you want
}
#Override
public void onItemLongClick(int position, View v) {
}
});
myActivity.mRecyclerView.setAdapter(mAdapter);