FirebaseRecyclerAdapter (sending list to UserAdapter class) - java

I am new to Android Studio..so please help me out.
I am working on app which shows the list of student in recycler view,I am retriving the list from Fire base Database but i'm getting the error at UserAdapter constructor class (I don't know what to provide in Super()).
I have used standard RecyclerAdapter it work the way I wanted but I couldn't get the UID of student when person clicks on it ....so I switched to FirebaseRecyclerAdapter ...here I can retrive the UID easily ...but getting error at constructor of UserAdapter.
I think I have to pass the FirebaseRecyclerOptions in my case its "options" but its show error
"Cannot reference 'UserAdapter.options' before supertype constructor has been called" and I don't know how to make the options Static.
I tried to make it static like this
public static FirebaseRecyclerOptions options;
in classmates class and accessed it in super() as super(classmates.this.options);i know its wrong method and then I declared in UserAdapter class but didnt work.
sorry for the long post.please help me out.
Here's the code:
public class classmates extends AppCompatActivity {
Toolbar toolbar;
private RecyclerView ClassmateList;
private DatabaseReference rDatabaseRef;
List<Users> list = new ArrayList<>();
FirebaseRecyclerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_classmates);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Classmates");
rDatabaseRef = FirebaseDatabase.getInstance().getReference().child("user");
ClassmateList = (RecyclerView) findViewById(R.id.recyclerView);
ClassmateList.setHasFixedSize(true);
ClassmateList.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
rDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot Snapshot) {
for (DataSnapshot dataSnapshot : Snapshot.getChildren()) {
Users studentDetails = dataSnapshot.getValue(Users.class);
list.add(studentDetails);
}
adapter = new UserAdapter(list, classmates.this);
ClassmateList.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public class UserAdapter extends FirebaseRecyclerAdapter<Users, UserAdapter.UserViewHolder> {
Context context1;
List<Users> InfoList;
FirebaseRecyclerOptions<Users> options =
new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(rDatabaseRef, Users.class)
.build();
public UserAdapter(List<Users> list, classmates classmates) {
super(); *<---ERROR ,DONT KNOW WHAT TO PROVIDE*
context1=classmates;
InfoList=list;
}
#Override
protected void onBindViewHolder(#NonNull UserViewHolder holder, int position, #NonNull Users model) {
final Users users = InfoList.get(position);
holder.setName(users.getName());
holder.setStatus(users.getStatus());
holder.setThumb_img(users.getThumb_img());
String userid=getRef(position).getKey();
}
#NonNull
#Override
public UserViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_singlelayout, parent, false);
UserViewHolder holder = new UserViewHolder(view);
return holder;
}
#Override
public int getItemCount() {
return InfoList.size();
}
public class UserViewHolder extends RecyclerView.ViewHolder {
View rview;
public UserViewHolder(View itemView) {
super(itemView);
rview = itemView;
}
public void setName(String name) {
TextView singleusername = (TextView) rview.findViewById(R.id.single_displayname);
singleusername.setText(name);
}
public void setStatus(String status) {
TextView singleuserstatus = (TextView) rview.findViewById(R.id.single_status);
singleuserstatus.setText(status);
}
public void setThumb_img(String thumb_image) {
CircleImageView user_img = (CircleImageView) rview.findViewById(R.id.single_thumb_image);
Picasso.get().load(thumb_image).placeholder(R.drawable.default_img).into(user_img);
}
}
}
}

Related

Passed data from Activity to Adapter, but when I try to use data as string, it displays as null

I have passed data from my Activity to My Adapter. When I debug, I can see the correct data has successfully passed to my adapter, but when I attempt to use it as a string ( for example, if I want to set the text as the data I just passed), it shows as null.
On the line that says " this.uniquesharedIds = uniquesharedId;" - the "uniqiuesharedIds" is showing as null.
"uniquesharedId" shows has the successfully passed data.
I need to be able to use the string of "uniqiuesharedIds."
Sorry if this is a silly question. Sending data from Activities to Adapters always confuses me and Im not able to find a ton of documentation/videos on the topic. Thank you.
My Activity In the On Create Method
myadapter = new Invite_Contributors_Adapter(contributorInviteList, getIntent().getStringExtra("uniquesharedId"));
The Adapter
public class Invite_Contributors_Adapter extends RecyclerView.Adapter<Invite_Contributors_Adapter.myviewholder> {
private ArrayList<Model_Invite_Contributors_List> model_invite_contributors_lists = new ArrayList<>();
FirebaseAuth mAuth;
private FirebaseUser currentuser;
private DatabaseReference UsersReference;
Context context;
String uniquesharedIds;
private InviteContributorsInterface inviteContributorsInterface;
public Invite_Contributors_Adapter() {
}
public void updateInviteList (ArrayList list) {
model_invite_contributors_lists .clear();
model_invite_contributors_lists .addAll(list);
notifyDataSetChanged();
}
public Invite_Contributors_Adapter(ArrayList<Model_Invite_Contributors_List>model_invite_contributors_lists, String uniquesharedId) {
this.model_invite_contributors_lists = model_invite_contributors_lists;
this.uniquesharedIds = uniquesharedId;
}
#NonNull
#Override
public Invite_Contributors_Adapter.myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout_invite_contributors_list, parent, false);
return new myviewholder(view);
}
#Override
public void onBindViewHolder(#NonNull myviewholder holder, int position) {
holder.setData(model_invite_contributors_lists.get(position));
mAuth = FirebaseAuth.getInstance();
holder.Name.setText(uniquesharedIds);
}
#Override
public int getItemCount() {
return model_invite_contributors_lists.size();
}
static class myviewholder extends RecyclerView.ViewHolder implements DialogInterface.OnClickListener {
TextView Name;
CircleImageView profileImageView;
public myviewholder(#NonNull View itemView) {
super(itemView);
Name = itemView.findViewById(R.id.contributor_name);
profileImageView = itemView.findViewById(R.id.member_profile_picture);
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
public void setData(Model_Invite_Contributors_List model) {
FirebaseUser currentuser;
currentuser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference NameRef = FirebaseDatabase.getInstance().getReference(Strings.UsersReference);
NameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//this is very important. this says to not show the current user in the list of people to invite as a contributor.//
if (currentuser.getUid().equals(model.getUser_Id())){
ViewGroup.LayoutParams params = itemView.getLayoutParams();
params.height = 0;
itemView.setLayoutParams(params);
} else {
for(DataSnapshot ds : dataSnapshot.getChildren())
{
itemView.setVisibility(View.VISIBLE);
String profileImageString;
profileImageString = model.getProfileimage();
Glide.with(profileImageView.getContext()) //pulling in image and telling the image which imageview to go to once it comes in from the database
.load(profileImageString)
.placeholder(R.drawable.circle_placeholder)
.error(R.drawable.circle_placeholder)
.into(profileImageView);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
public void setInterface (Invite_Contributors_Adapter.InviteContributorsInterface inviteContributorsInterface) {
this.inviteContributorsInterface = inviteContributorsInterface;
}
public interface InviteContributorsInterface{
}
}
Are you using any primary constructor of the adapter like this?
myadapter = new Invite_Contributors_Adapter();
If yes, then that's where the problem is. If you're initializing object with two different constructors then you'll get the value of the object which you initialized later.
Make sure to check the adapter object & then proceed.

I can't use getRef in onBingViewHolder method, I'm trying to show selected item in another view

I'm trying to show the selected items in another view and I can't get the key using getRef method. How should I get the key to pass the data? I tried to find similar solutions on StackOverflow but just can't find it...
This is my onBindViewHolder:
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
final String productKey = getRef(position).getKey();
holder.textViewName.setText(uploadCurrent.getName());
//Picasso.with(mContext).load(uploadCurrent.getmImageUrl()).fit().centerCrop().into(holder.imageView);
Glide.with(mContext).asBitmap().load(uploadCurrent.getmImageUrl()).into(holder.imageView);
holder.v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mContext, SingleProductActivity.class);
i.putExtra("ProductKey", productKey);
mContext.startActivity(i);
}
});
}
And my class where I'm trying to show upload data.
String productKey = getIntent().getStringExtra("ProductKey");
mDatabaseRef.child(productKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String productName = snapshot.child("mName").getValue().toString();
String productDesc = snapshot.child("mDescription").getValue().toString();
String imageUrl = snapshot.child("mImageUrl").getValue().toString();
productDescriptionTxt.setText(productDesc);
singleProductNameTxt.setText(productName);
productPriceTagTxt.setText("100");
Glide.with(mContext).asBitmap().load(imageUrl).into(singleProductImg);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Here is my whole adapter
public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
private Context mContext;
private List<Upload> mUploads;
private String link;
private DatabaseReference mDatabaseRef;
public ImageAdapter(Context context, List<Upload> uploads) {
this.mContext = context;
this.mUploads = uploads;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.product_item, parent, false);
return new ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
final String productKey = getRef(position).getKey();
holder.textViewName.setText(uploadCurrent.getName());
//Picasso.with(mContext).load(uploadCurrent.getmImageUrl()).fit().centerCrop().into(holder.imageView);
Glide.with(mContext).asBitmap().load(uploadCurrent.getmImageUrl()).into(holder.imageView);
holder.v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mContext, SingleProductActivity.class);
i.putExtra("ProductKey", productKey);
mContext.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder{
public TextView textViewName;
public ImageView imageView;
private CardView parent;
private View v;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
parent = itemView.findViewById(R.id.parent);
textViewName = itemView.findViewById(R.id.productNameTxt);
imageView = itemView.findViewById(R.id.productImg);
//v označava jedan prikazan item
v = itemView;
}
}
}
As I see, your ImageAdapter class extends RecyclerView.Adapter. That being said, you are getting the following error:
Cannot resolve method 'getRef' in 'ImageAdapter'.
Because the RecyclerView.Adapter class doesn't contain any getRef() method inside it, hence the error. However, FirebaseRecyclerAdapter does. As you can see, the getRef() method is present in the FirebaseRecyclerAdapter class and not in the RecyclerView.Adapter class.
To solve this, you either adapt to the code of the Firebase-UI library, or you keep using the RecyclerView.Adapter and get the "productKey" like so:
Upload uploadCurrent = mUploads.get(position);
String productKey = uploadCurrent.getProductKey();
But this will only work if you have the productKey as a field inside the Upload class. If you don't have it yet, add it and populate it when you add data to the database.

Changes to RecyclerView led to this Error :E/RecyclerView: No adapter attached; skipping layout

After implementing all the Recyclerview codes, i still end up with this Error :E/RecyclerView: No adapter attached; skipping layout.
Im not sure if it is because of the layout or where it is placed...
I changed the location of it multiple times and i had to revert back to an older version as some of the solutions i found on the internet caused it to crash.
public class MainMenu extends AppCompatActivity implements
IFirebaseLoadListener {
private Context context;
private List<ItemData> itemDataList;
private List<ItemGroup> dataList;
AlertDialog dialog;
IFirebaseLoadListener iFirebaseLoadListener;
RecyclerView my_recycler_view;
DatabaseReference myData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
myData = FirebaseDatabase.getInstance().getReference("Data");
dialog = new SpotsDialog.Builder().setContext(this).build();
iFirebaseLoadListener = this;
//View
my_recycler_view = (RecyclerView)findViewById(R.id.my_recyclr_view);
my_recycler_view.setHasFixedSize(true);
my_recycler_view.setLayoutManager(new LinearLayoutManager(this));
getFirebaseData();
}
private void getFirebaseData () {
dialog.show();
myData.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange (#NonNull DataSnapshot dataSnapshot) {
List<ItemGroup> itemGroups =new ArrayList<>();
for(DataSnapshot groupSnapShot:dataSnapshot.getChildren()){
ItemGroup itemGroup = new ItemGroup();
itemGroup.setHeaderTitle(groupSnapShot.child("headerTitle").getValue (String.class));
GenericTypeIndicator<ArrayList<ItemData>> genericTypeIndicator =new GenericTypeIndicator<ArrayList<ItemData>>(){};
itemGroup.setListItem(groupSnapShot.child("listItem").getValue(genericTypeIndicator));
itemGroups.add(itemGroup);
}
iFirebaseLoadListener.onFirebaseLoadSuccess(itemGroups);
}
#Override
public void onCancelled (#NonNull DatabaseError databaseError) {
iFirebaseLoadListener.onFirebaseLoadFailed(databaseError.getMessage());
}
});
}
#Override
public void onFirebaseLoadSuccess(List<ItemGroup> itemGroupList) {
MyItemGroupAdapter adapter = new
MyItemGroupAdapter(this,itemGroupList);
my_recycler_view.setAdapter(adapter);
dialog.dismiss();
}
#Override
public void onFirebaseLoadFailed(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
}
I have 2 other pages for my Adapters, "MyItemAdapter" and "MyItemGroupAdapter"
but im not sure why it isnt able to call them
My Adapters:
public class MyItemAdapter extends RecyclerView.Adapter<MyItemAdapter.MyViewHolder> {
private Context context;
private List<ItemData> itemDataList;
public MyItemAdapter(Context context, List<ItemData> itemDataList) {
this.context = context;
this.itemDataList = itemDataList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(context).inflate(R.layout.layout_item,viewGroup,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
myViewHolder.txt_item_title.setText(itemDataList.get(i).getName());
Picasso.get().load(itemDataList.get(i).getArt()).into(myViewHolder. img_item);
myViewHolder.setiItemClickListener(new IItemClickListener() {
#Override
public void onItemClickListener(View view, int position) {
Toast.makeText(context, ""+itemDataList.get(i).getName(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {return (itemDataList != null ? itemDataList.size() : 0);
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView txt_item_title;
ImageView img_item;
IItemClickListener iItemClickListener;
public void setiItemClickListener(IItemClickListener iItemClickListener) {
this.iItemClickListener = iItemClickListener;
}
public MyViewHolder(#NonNull View itemView) {
super(itemView);
txt_item_title = itemView.findViewById(R.id.name);
img_item = itemView.findViewById(R.id.art);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
iItemClickListener.onItemClickListener(view,getAdapterPosition());
}
}
}
There's no data for your RecyclerView to display when the view is created.
Inside of your onCreate you should create your adapter with empty or null data then call setAdapter() on your RecyclerView using the empty adapter. Later, you can update the adapter with new data and call notifyDataSetChanged() on your adapter to refresh it.

How to fix null pointer from firebase when getting a key?

I got an error, for not getting data from firebase, I don't know why but I try to set the key to my modeldata. And when I try to put it on Recycleview. I got an error when I tried to get the data.
Take a look at my code.
ListActivity
public class ListActivity extends BaseActivity {
private DatabaseReference databaseReference;
private RecyclerView labelRecycleView;
private ArrayList<DataFirebase> listLabel;
private listAdapter listAdapter;
private Button bInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
findView();
setDataToList();
initListener();
putLayoutManager();
}
private void setDataToList() {
simpleway.progressDialog(ListActivity.this);
databaseReference.child("Username").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
listLabel = new ArrayList<>();
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
DataFirebase modelClass = dataSnap.getValue(DataFirebase.class);
modelClass.setLabel(dataSnap.getKey());
listLabel.add(modelClass);
}
listAdapter = new listAdapter(listLabel, ListActivity.this);
labelRecycleView.setAdapter(listAdapter);
simpleway.stopProgressDialog();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println(databaseError.getDetails() + " " + databaseError.getMessage());
simpleway.stopProgressDialog();
}
});
}
private void putLayoutManager() {
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
labelRecycleView.setLayoutManager(layoutManager);
labelRecycleView.setItemAnimator(new DefaultItemAnimator());
}
#Override
public void findView() {
databaseReference = FirebaseDatabase.getInstance().getReference();
labelRecycleView = findViewById(R.id.listRecyclerVIew);
bInput = findViewById(R.id.inputData);
}
#Override
public void initListener() {
bInput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
simpleway.startnextActivity(ListActivity.this, InputActivity.class);
}
});
}
}
and this is my adapter it show that i cant get data from my label.
ListAdapter
public class listAdapter extends RecyclerView.Adapter<listAdapter.ViewHolder> {
private List<DataFirebase> dataList;
private AppCompatActivity someActivity;
public listAdapter(List<DataFirebase> dataFirebases, AppCompatActivity someActivity) {
this.dataList = dataFirebases;
this.someActivity = someActivity;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_label, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
final DataFirebase labelList = dataList.get(i);
viewHolder.textLabel.setText(labelList.getLabel());
viewHolder.linearLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
someActivity.getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_right)
.replace(R.id.container_layout, new TitleFragment())
.commit();
}
});
}
#Override
public int getItemCount() {
return dataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public LinearLayout linearLabel;
public TextView textLabel;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textLabel = itemView.findViewById(R.id.text_label);
linearLabel = itemView.findViewById(R.id.linearLabel);
}
}
}
its perfectly fine before I try to install for the second time. the data are showed up just fine but the second time I try to install I got this error.
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.parzival.flashcard.adapter.listAdapter.onBindViewHolder(listAdapter.java:45)
at com.example.parzival.flashcard.adapter.listAdapter.onBindViewHolder(listAdapter.java:23)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
How can I fix this?
Going by the stack trace, your textview is null.
textLabel = itemView.findViewById(R.id.text_label);
linearLabel = itemView.findViewById(R.id.linearLabel);
Make sure that your text_label / linearLabel id belongs to R.layout.item_label.
Please show your data structure
add this in your code:
if (modelClass != null){
modelClass.setLabel(dataSnap.getKey());
}

Android Dont know how to fix this index out of bounds exception FirebaseRecyclerview

I get this error and I dont know how to fix it
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.get(ArrayList.java:411)
at com.tijdelijk.firebasetest.Start$1.populateViewHolder(Start.java:69)
at com.tijdelijk.firebasetest.Start$1.populateViewHolder(Start.java:64)
I am working with firebase database and based on CategoryId I put the items in a arraylist for the SubCategories my code:
public class CategoryFragment extends Fragment {
View myFragment;
RecyclerView listCategory;
RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<Category, CategoryViewHolder> adapter;
FirebaseDatabase database;
DatabaseReference categories;
DatabaseReference subCategory;
public static CategoryFragment newInstance() {
CategoryFragment fragment = new CategoryFragment();
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
categories = database.getReference("Category");
subCategory = database.getReference("SubCategory");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myFragment = inflater.inflate(R.layout.fragment_category, container, false);
listCategory = (RecyclerView) myFragment.findViewById(R.id.listCategory);
listCategory.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(container.getContext());
listCategory.setLayoutManager(layoutManager);
loadCategories();
return myFragment;
}
private void loadCategories() {
adapter = new FirebaseRecyclerAdapter<Category, CategoryViewHolder>(
Category.class,
R.layout.category_layout,
CategoryViewHolder.class,
categories
) {
#Override
protected void populateViewHolder(CategoryViewHolder viewHolder, final Category model, int position) {
viewHolder.category_name.setText(model.getName());
Picasso.with(getActivity())
.load(model.getImage())
.into(viewHolder.category_image);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent startGame = new Intent(getActivity(), Start.class);
Common.categoryId = adapter.getRef(position).getKey();
loadSubCategory(Common.categoryId);
startActivity(startGame);
}
});
}
};
adapter.notifyDataSetChanged();
listCategory.setAdapter(adapter);
}
private void loadSubCategory(String categoryId) {
//Clear list if there are old subCategory
if (Common.subCategoryList.size() > 0) {
Common.subCategoryList.clear();
}
subCategory.orderByChild("CategoryId").equalTo(categoryId)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
SubCategory ques = postSnapshot.getValue(SubCategory.class);
Common.subCategoryList.add(ques);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
in this activity I want to display also a recyclerview but this time based on the arraylist I got from the categoryfragment here is my code:
public class Start extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference subCategory;
FirebaseRecyclerAdapter<SubCategory, SubCategoryViewHolder> adapter;
RecyclerView listSubCategory;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
database = FirebaseDatabase.getInstance();
subCategory = database.getReference("SubCategory");
listSubCategory = findViewById(R.id.listSubCategory);
listSubCategory.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getBaseContext());
listSubCategory.setLayoutManager(layoutManager);
loadSubCategories();
adapter.notifyDataSetChanged();
listSubCategory.setAdapter(adapter);
}
private void loadSubCategories() {
adapter = new FirebaseRecyclerAdapter<SubCategory, SubCategoryViewHolder>(
SubCategory.class,
R.layout.subcategory_layout,
SubCategoryViewHolder.class,
subCategory
) {
#Override
protected void populateViewHolder(SubCategoryViewHolder viewHolder, SubCategory model, int position) {
viewHolder.subcategory_nlname.setText(Common.subCategoryList.get(position).getLatijnseNaam());
viewHolder.subcategory_ltname.setText(Common.subCategoryList.get(position).getNederlandseNaam());
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent startGame = new Intent(Start.this, Start.class);
Common.categoryId = adapter.getRef(position).getKey();
startActivity(startGame);
}
});
}
};
}
}
here is my viewholder:
public class SubCategoryViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener{
public TextView subcategory_nlname;
public TextView subcategory_ltname;
private ItemClickListener itemClickListener;
public SubCategoryViewHolder(View itemView) {
super(itemView);
subcategory_ltname = itemView.findViewById(R.id.latijnse_naam);
subcategory_nlname = itemView.findViewById(R.id.nederlandse_naam);
// itemView.findViewById(R.id.btnPlay).setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
IndexOutOfBoundException means that you are trying to access a value that is at an index out of the array.
In your case, you have an array of two values. So you have the keys 0 and 1. As said in the error, your code is trying to access the index 2, which does not exist.
You have to check that you are accessing an index that is in the range of values of the array.
Good day to you.

Categories