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);
Related
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!
DATABASE
I wanted to retrieve all the value from my firebase, but it retrieved the last one only which is "hjh" , what did i do wrong?
This is my code
public class MainActivity extends AppCompatActivity {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("content");
ArrayList<String> postList = new ArrayList<>();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference contentRef = rootRef.child("Post");
ValueEventListener value_l;
TextView content_view;
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
//setContentView(R.layout.post_info);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
content_view = (TextView) findViewById(R.id.contentTextview);
listview = (ListView) findViewById(R.id.listview);
value_l = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
String contentText = ds.child("content").getValue(String.class);
postList.add(contentText);
//FOR ARRAYLIST TESTING content_view.setText(postList.get(postList.size()-1));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
};
Thank you :)
You should try this code it may be help you.
1) MainActivity
public class MainActivity extends AppCompatActivity {
private RecyclerView rvData;
private RetriveDataAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rvData = findViewById(R.id.rvData);
rvData.setHasFixedSize(true);
rvData.setLayoutManager(new LinearLayoutManager(MainActivity.this));
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("Post").addValueEventListener(new ValueEventListener() {
#SuppressLint("LongLogTag")
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<MyBean> arrayList = new ArrayList<MyBean>();
for (DataSnapshot noteDataSnapshot : dataSnapshot.getChildren()) {
MyBean bean = noteDataSnapshot.getValue(MyBean.class);
arrayList.add(bean);
}
Log.e("MainActivity.this", "Data list ::>>>>>" + arrayList.size());
adapter = new RetriveDataAdapter(MainActivity.this, arrayList);
rvData.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
2) MyBean
public class MyBean {
public String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
3) RetriveDataAdapter
public class RetriveDataAdapter extends RecyclerView.Adapter<RetriveDataAdapter.MyViewHolder> {
private static final String TAG = "RetriveDataAdapter.class";
private Context ctx;
private ArrayList<MyBean> dataList;
#SuppressLint("LongLogTag")
public RetriveDataAdapter(Context context, ArrayList<MyBean> dataList) {
this.ctx = context;
this.dataList = dataList;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView tvContent;
public MyViewHolder(View view) {
super(view);
tvContent = view.findViewById(R.id.tvContent);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_form, parent, false);
return new MyViewHolder(itemView);
}
#SuppressLint("LongLogTag")
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final MyBean bean = dataList.get(position);
holder.tvContent.setText("Content: " + bean.getContent());
}
#Override
public int getItemCount() {
return dataList.size();
}
}
I can't see your whole Database's structure and didn't see where you call addValueEventListener(value_l) , so that I can only guess it's because of the wrong level Reference.
You should add value_l to the correct reference, maybe all the post's parent, and iterate through all of it's child using snapshot.forEach()
Google for firebase database iterate may provides more detailed information.
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());
}
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