I am using a recyclerview to show cardview elements, and have made an adapter for the same. When I use an Arraylist to store the values, the recyclerview works as expected and the elements show. Howver, I want to use a linked list as items are constantly added and deleted. When I try to use a linked list, the recyclerview doesn't work and the elements don't show. How can I fix this?
My class code:
public class AdminViewAlertsActivity extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference database;
AlertAdapter alertAdapter;
ArrayList<AlertModel> list;
LinkedList<AlertModel> list2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_view_alerts);
recyclerView = findViewById(R.id.alerts_list);
database = FirebaseDatabase.getInstance().getReference("Alerts");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
list2 = new LinkedList<>();
alertAdapter = new AlertAdapter(this,list2);
recyclerView.setAdapter(alertAdapter);
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot:snapshot.getChildren()){
AlertModel alertModel = dataSnapshot.getValue(AlertModel.class);
list.add(alertModel);
alertAdapter.notifyDataSetChanged();
}
alertAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
My adapter code:
public class AlertAdapter extends RecyclerView.Adapter<AlertAdapter.AlertViewHolder> {
Context context;
LinkedList<AlertModel> list;
AlertAdapter adapter;
public AlertAdapter(Context context, LinkedList<AlertModel> list) {
this.context = context;
this.list = list;
this.adapter = this;
}
#NonNull
#Override
public AlertViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.alrtitem,parent,false);
return new AlertViewHolder(v);
}
interface Interactions{
public void refreshActivity();
}
#Override
public void onBindViewHolder(#NonNull AlertViewHolder holder, int position) {
AlertModel alertModel = list.get(position);
holder.date_and_time.setText(alertModel.getDate_time());
holder.alert.setText(alertModel.getNotification());
holder.viewOptions.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupMenu popup = new PopupMenu(context, holder.viewOptions);
popup.inflate(R.menu.alertmenu);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.alertmenu1:
DatabaseReference dataRef = FirebaseDatabase.getInstance().getReference();
dataRef.child("Alerts").child(alertModel.getDate_time()).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
list.remove(holder.getBindingAdapterPosition());
adapter.notifyDataSetChanged();
}
});
default:
return false;
}
}
});
popup.show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public static class AlertViewHolder extends RecyclerView.ViewHolder{
TextView date_and_time, alert, viewOptions;
public AlertViewHolder(#NonNull View itemView) {
super(itemView);
date_and_time = itemView.findViewById(R.id.date_and_time);
alert = itemView.findViewById(R.id.Alert);
viewOptions = itemView.findViewById(R.id.viewOptions);
}
}
}
Any help is appreciated!
Related
I am having trouble with shuffling images in home screen in a wallpaper app. i want like when ever a person opens my app the images in the home screen should be shuffled . i tried using Collections.shuffle() method, in using that what is happening is the images are getting duplicated and when i click on the shuffled image to open in fullscreen some other image opens
suppose in a list A(0,1,2,3) when i shuffle it only the display changes but when i open it itopens according to the index of list A
please help me with the code as to where and how i have to use the Collections.shuffle method
here is my code .
I am troubled for many days and not getting the solution so please help
Homescreen.java
public class Homescreen extends AppCompatActivity {
RecyclerView recyclerView;
List<WallpaperModel> list;
private WallpaperAdapter adapter;
DatabaseReference reference;
public static final String TAG = Homescreen.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
init();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this,3));
list = new ArrayList<>();
adapter.shuffle();
adapter.notifyDataSetChanged();
adapter = new WallpaperAdapter(list);
recyclerView.setAdapter(adapter);
reference = FirebaseDatabase.getInstance().getReference().child("Wallpapers");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
list.clear();
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
WallpaperModel model = dataSnapshot.getValue(WallpaperModel.class);
list.add(model);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.e(TAG,error.getMessage());
}
});
}
private void
init(){
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = findViewById(R.id.recyclerView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.favourite){
startActivity(new Intent(Homescreen.this, FavouriteActivity.class));
}
return true;
}
}
and this is my wallpaperAdapter class
public class WallpaperAdapter extends
RecyclerView.Adapter<WallpaperAdapter.WallpaperHolder> {
private static List<WallpaperModel> list;
public WallpaperAdapter(List<WallpaperModel> list) {
WallpaperAdapter.list = list;
}
#NonNull
#Override
public WallpaperHolder onCreateViewHolder(#NonNull ViewGroup parent, int
viewType) {
View view =
LayoutInflater.from(parent.getContext())
.inflate(R.layout.wallpaper_items,parent,false);
return new WallpaperHolder(view);
}
#Override
public void onBindViewHolder(#NonNull
WallpaperAdapter.WallpaperHolder holder, int position) {
Random random = new Random();
int color = Color.rgb(0,0,0);
Glide.with(holder.itemView.getContext().getApplicationContext())
.load(list.get(position).getImage())
.timeout(7500)
.into(holder.imageView);
holder.setClickListener();
}
#Override
public int getItemCount() {
return list.size();
}
public void shuffle() {
Collections.shuffle(list,new Random(System.currentTimeMillis()));
}
static class WallpaperHolder extends RecyclerView.ViewHolder{
private ImageView imageView;
public WallpaperHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
}
void setClickListener(){
//set on click listener on wallpaper image
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Intent intent = new Intent(itemView.getContext().getApplicationContext(),
SwiperActivity.class);
intent.putExtra("position",position);
itemView.getContext().startActivity(intent);
}
});
}
}
}
This Is My MainActivity.
public class MatchContests extends AppCompatActivity implements ItemClickListener {
RecyclerView recyclerView;
private DatabaseReference myref;
private ArrayList<ZgetsetContests> contestsList;
private AdapterContests adapterContests;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match_contests);
recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapterContests.setClickListener(this);
myref = FirebaseDatabase.getInstance().getReference();
contestsList = new ArrayList<>();
ClearAll();
GetContestDetails();
}
private void GetContestDetails()
{
Query query = myref.child("contestsdetails").child("match1");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ClearAll();
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
ZgetsetContests zgetsetContests = new ZgetsetContests();
zgetsetContests.setEntry(snapshot.child("entry").getValue().toString());
zgetsetContests.setBonususage(snapshot.child("bonususage").getValue().toString());
zgetsetContests.setFirstposition(snapshot.child("firstposition").getValue().toString());
zgetsetContests.setMaintitle(snapshot.child("maintitle").getValue().toString());
zgetsetContests.setTeamsallowed(snapshot.child("teamsallowed").getValue().toString());
zgetsetContests.setTotalspots(snapshot.child("totalspots").getValue().toString());
zgetsetContests.setPrizepool(snapshot.child("prizepool").getValue().toString());
contestsList.add(zgetsetContests);
}
adapterContests = new AdapterContests(getApplicationContext(),contestsList);
recyclerView.setAdapter(adapterContests);
adapterContests.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void ClearAll()
{
if (contestsList != null) {
contestsList.clear();
if (adapterContests != null){adapterContests.notifyDataSetChanged();}
}
contestsList = new ArrayList<>();
}
#Override
public void onClick(View v, int position) {
}
}
My Adapter Class.
public class AdapterContests extends RecyclerView.Adapter<AdapterContests.ViewHolder> {
private static final String Tag = "RecyclerView";
private Context mContext;
private ArrayList<ZgetsetContests> contestsList;
private DatabaseReference dr;
private ItemClickListener clickListener;
public AdapterContests(Context mContext, ArrayList<ZgetsetContests> contestsList) {
this.mContext = mContext;
this.contestsList = contestsList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.design_contests,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
holder.entry.setText(contestsList.get(position).getEntry());
holder.prizepool.setText(contestsList.get(position).getPrizepool());
holder.firstposition.setText(contestsList.get(position).getFirstposition());
holder.totalspots.setText(contestsList.get(position).getTotalspots());
holder.teamsallowed.setText(contestsList.get(position).getTeamsallowed());
holder.bonususage.setText(contestsList.get(position).getBonususage());
holder.maintitle.setText(contestsList.get(position).getMaintitle());
holder.progressBar.setMax(Integer.parseInt(contestsList.get(position).getTotalspots()));
dr = FirebaseDatabase.getInstance().getReference().child("match1joinedteams").child("contest1");
dr.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
Long countjoinedteams1 = dataSnapshot.getChildrenCount();
int a = countjoinedteams1.intValue();
holder.progressBar.setProgress(a);
}else{ }
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public int getItemCount() {
return contestsList.size();
}
public void setClickListener(ItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView maintitle;
TextView entry;
TextView prizepool;
TextView firstposition;
TextView teamsallowed;
TextView bonususage;
TextView totalspots;
ProgressBar progressBar;
public ViewHolder(#NonNull View itemView) {
super(itemView);
maintitle = itemView.findViewById(R.id.maintitle1);
entry = itemView.findViewById(R.id.entry1);
prizepool = itemView.findViewById(R.id.prizepool1);
firstposition = itemView.findViewById(R.id.firstpoisition1);
teamsallowed = itemView.findViewById(R.id.teamsallowed1);
bonususage = itemView.findViewById(R.id.bonususage1);
totalspots = itemView.findViewById(R.id.totalspots1);
progressBar = itemView.findViewById(R.id.progressbar1);
itemView.setTag(itemView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (clickListener != null) clickListener.onClick(v, getAdapterPosition());
}
}
}
AppCrashes When I Enter The Activity.
Problem is In MainActivity On Line adapterContests.setClickListener(this); Logcat Shows Attempt To Invoke Virtual Method on null Object.
When I Remove This Line App Works Fine But Click Listener Will Not Be Working.
Before When i was only retriving data app was working fine but after implementing onClick App Crashed
Well you call the method on the adapter when it isn't initialized yet.
Do you see this line:
adapterContests.setClickListener(this);
Move it under these:
..............
adapterContests = new AdapterContests(getApplicationContext(),contestsList);
recyclerView.setAdapter(adapterContests);
//here...
adapterContests.notifyDataSetChanged();
..........
UPDATE:
//SHOULD BE LIKE THIS
adapterContests.setClickListener(MatchContests.this);
I am new begginer to android. What I am trying is to make an app that people can share images with each other.(similar to instagram) I am using firebase store and storage for that. Adding a new image on a recyclerview is not a problem and also I would like to remove the item when I longclick on it. But in my case when I longclick the item, not only the item is removed but also the rest of the items are dublicated.I added an example picture here.problem example
But once I restart the app list seems fine without any dublication.
here is my feed screen code;
public class FeedActivity extends AppCompatActivity implements FeedRecyclerAdapter.OnNoteListener {
private FirebaseAuth firebaseAuth;
private FirebaseFirestore firebaseFirestore;
private FirebaseStorage firebaseStorage;
private StorageReference storageReference;
ArrayList<String> userEmailFromFB;
ArrayList<String> usercommentFromFB;
ArrayList<String> userImageFromFB;
FeedRecyclerAdapter feedRecyclerAdapter;
ArrayList<String> dokumanl;
ArrayList<String> namel;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.insta_options_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()== R.id.add_post){
Intent intentToUpload=new Intent(FeedActivity.this, UploadActivity.class);
startActivity(intentToUpload);
}else if (item.getItemId()==R.id.signout){
firebaseAuth.signOut();
Intent intentToSignUp=new Intent(FeedActivity.this,SignUpActivity.class);
startActivity(intentToSignUp);
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feed);
usercommentFromFB=new ArrayList<>();
userEmailFromFB=new ArrayList<>();
userImageFromFB=new ArrayList<>();
dokumanl =new ArrayList<>();
namel=new ArrayList<>();
firebaseStorage = FirebaseStorage.getInstance();
storageReference= firebaseStorage.getReference();
firebaseAuth=FirebaseAuth.getInstance();
firebaseFirestore=FirebaseFirestore.getInstance();
RecyclerView recyclerView=findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
feedRecyclerAdapter= new FeedRecyclerAdapter(userEmailFromFB,usercommentFromFB,userImageFromFB, this);
recyclerView.setAdapter(feedRecyclerAdapter);
getDataFromFirestore();
}
public void getDataFromFirestore(){
CollectionReference collectionReference=firebaseFirestore.collection("Posts");
collectionReference.orderBy("date", Query.Direction.DESCENDING).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (e != null){
Toast.makeText(FeedActivity.this, e.getLocalizedMessage().toString(), Toast.LENGTH_LONG).show();
}
if( queryDocumentSnapshots != null){
for( DocumentSnapshot snapshot: queryDocumentSnapshots.getDocuments()){
Map<String,Object> data= snapshot.getData();
String comment= (String)data.get("comment");
String userEmail=(String)data.get("useremail");
String downloadUrl= (String)data.get("downloadurl");
String dokuman= snapshot.getId();
String name= (String)data.get("name");
usercommentFromFB.add(comment);
userEmailFromFB.add(userEmail);
userImageFromFB.add(downloadUrl);
dokumanl.add(dokuman);
namel.add(name);
feedRecyclerAdapter.notifyDataSetChanged();
}
}
}
});
}
#Override
public void onNoteClick(int position) {
//System.out.println("position:"+ namel.get(position));
StorageReference desertRef= storageReference.child(namel.get(position));
desertRef.delete();
firebaseFirestore.collection("Posts").document(dokumanl.get(position))
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(FeedActivity.this, "Silindi", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
usercommentFromFB.remove(position);
userImageFromFB.remove(position);
userEmailFromFB.remove(position);
dokumanl.remove(position);
namel.remove(position);
feedRecyclerAdapter.notifyDataSetChanged();
}
}
Also here is my adapter code;
public class FeedRecyclerAdapter extends RecyclerView.Adapter<FeedRecyclerAdapter.PostHolder> {
private ArrayList<String> userEmailList;
private ArrayList<String> userCommentList;
private ArrayList<String> userImageList;
private OnNoteListener mOnNoteListener;
public FeedRecyclerAdapter(ArrayList<String> userEmailList, ArrayList<String> userCommentList, ArrayList<String> userImageList, OnNoteListener onNoteListener) {
this.userEmailList = userEmailList;
this.userCommentList = userCommentList;
this.userImageList = userImageList;
this.mOnNoteListener= onNoteListener;
}
#NonNull
#Override
public PostHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater=LayoutInflater.from(parent.getContext());
View view=layoutInflater.inflate(R.layout.recycler_row,parent,false);
return new PostHolder(view, mOnNoteListener);
}
#Override
public void onBindViewHolder(#NonNull PostHolder holder, int position) {
holder.userEmailText.setText(userEmailList.get(position));
holder.commentText.setText(userCommentList.get(position));
Picasso.get().load(userImageList.get(position)).into(holder.imageView);
}
#Override
public int getItemCount() {
return userEmailList.size();
}
class PostHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener {
ImageView imageView;
TextView userEmailText;
TextView commentText;
OnNoteListener onNoteListener;
public PostHolder(#NonNull View itemView, OnNoteListener onNoteListener) {
super(itemView);
imageView=itemView.findViewById(R.id.recyclerView_row_imageview);
userEmailText=itemView.findViewById(R.id.recyclerView_row_useremail_text);
commentText=itemView.findViewById(R.id.recyclerView_row_comment_text);
this.onNoteListener=onNoteListener;
itemView.setOnLongClickListener(this);
}
#Override
public boolean onLongClick(View v) {
onNoteListener.onNoteClick(getAdapterPosition());
return false;
}
}
public interface OnNoteListener{
void onNoteClick(int position);
}
}
Try this:
In your onNoteClick(int position) method in your FeedActivity:
Move these lines:
usercommentFromFB.remove(position);
userImageFromFB.remove(position);
userEmailFromFB.remove(position);
dokumanl.remove(position);
namel.remove(position);
feedRecyclerAdapter.notifyDataSetChanged();
Directly in the addOnSuccessListener:
........
........
firebaseFirestore.collection("Posts").document(dokumanl.get(position))
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(FeedActivity.this, "Silindi", Toast.LENGTH_LONG).show();
//here..........
}
})
..........
..........
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.
I tried to change the database in the console firebase but the data in my adapter unchanged, recylerview was only changed when the application is closed and opened again
MainActivity.java
public class MainActivity extends AppCompatActivity {
private List<ModelDB> dbList = new ArrayList<>();
private AdapterDB adapter;
private RecyclerView recyclerView;
FirebaseDatabase database;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFirebase();
getData();
initRecylerView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_person:
Intent intent = new Intent(getApplicationContext(),RegisterActivity.class);
startActivity(intent);
break;
default:
Toast.makeText(getApplicationContext(),"lalalala",Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}
private void initFirebase(){
database = FirebaseDatabase.getInstance();
reference = database.getReference("user");
}
private void initRecylerView(){
recyclerView = (RecyclerView)findViewById(R.id.rv_list);
recyclerView.setHasFixedSize(true);
adapter = new AdapterDB(dbList);
recyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
}
private void getData() {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//loop data all user
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
//instance object to get and set data
ModelDB modelDB = postSnapshot.getValue(ModelDB.class);
//adding data list from object
dbList.add(modelDB);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
AdapterDB.java
public class AdapterDB extends RecyclerView.Adapter<AdapterDB.MyViewHolder> {
private List<ModelDB> modelDBList;
public AdapterDB(List<ModelDB> modelDBList) {
this.modelDBList = modelDBList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_data,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ModelDB modelDB = modelDBList.get(position);
holder.tv_nama.setText(modelDB.getNama());
holder.tv_alamat.setText(modelDB.getAlamat());
}
#Override
public int getItemCount() {
return modelDBList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv_nama, tv_alamat;
public MyViewHolder(View itemView) {
super(itemView);
tv_nama = (TextView) itemView.findViewById(R.id.tv_nama);
tv_alamat = (TextView) itemView.findViewById(R.id.tv_alamat);
}
}
}
You need to kind of let the adapter know that the data has changed and that the UI has to be refreshed or whatever. The OnDataChange in your code should be like this (check the last line within the method) -
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//loop data all user
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
//instance object to get and set data
ModelDB modelDB = postSnapshot.getValue(ModelDB.class);
//adding data list from object
dbList.add(modelDB);
adapter.notifyDataSetChanged();
}
}
This should do the trick assuming there are no other bugs in some other parts of your code