Aswin Raj K :
I am using Firebase as a back-end system and I am also using the Recycler View for displaying the data to the user. But when fetching data from the database the getValue()
method returns null
.
I have attached my code below:
public class Post {
private String desc;
private String image;
public Post()
{}
public Post(String desc,String image)
{
this.image= image;
this.desc = desc;
}
public String getDescription()
{
return desc;
}
public String getImage(){
return image;
}
}
The code for MainActivity:
public class fragment2Activity extends Fragment {
private RecyclerView recyclerView;
private RecyclerView.Adapter madapter;
private RecyclerView.LayoutManager layoutManager;
private View view;
private ArrayList<Post> postArrayList;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment2, container, false);
final DatabaseReference mref= FirebaseDatabase.getInstance().getReference().child("Post");
recyclerView = (RecyclerView)view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
mref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot childSnapShot : dataSnapshot.getChildren()) {
Post p = childSnapShot.getValue(Post.class);
postArrayList.add(p);
}
madapter = new MyAdapter(postArrayList);
recyclerView.setAdapter(madapter);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
return view;
}
}
My database:
logcat:
Can anyone find a solution?
Frank van Puffelen :
You never initialize postArrayList
, so postArrayList.add(p);
is causing a NullPointerException
.
The solution is to create postArrayList
, typically in the onCreate
:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment2, container, false);
final DatabaseReference mref= FirebaseDatabase.getInstance().getReference().child("Post");
recyclerView = (RecyclerView)view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
postArrayList = new ArrayList<Post>(); // <-- this is new
mref.addListenerForSingleValueEvent(new ValueEventListener() {
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=220471&siteId=1