why realtime database can not work in my recyclerview - java

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

Related

RecyclerView elements dont show when using Linkedlist

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!

Shuffling images

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);
}
});
}
}
}

Implemented On Click Event On RecyclerView,But App Crashes

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);

How to retrieve all value from firebase?

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.

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());
}

Categories