How to retrieve data from Firebase on other activity? - android

I am making an application in which I am saving data on one page that is RequestOrder on Firebase Realtime Database and I want to retrieve it on other page that is PendingOrder.
I am using tablayouts with fragment one tab showing PendingOrder and the one showing completed order. After Googling a lot I have come to the point that everyone is using ListView to retrieve data from Firebase.
I try to do the same but am stuck in an error. Please help me out.
The error is "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.hp.another.ServiceConsumer.getPkgDetail()' on a null object reference"
public class PendingOrder extends Fragment {
DatabaseReference databaseReference;
FirebaseDatabase firebaseDatabase;
FirebaseAuth.AuthStateListener mAuthListener;
ListView listView1;
String userId;
List<ServiceConsumer> consumerList;
private static final String TAG = "PendingOrder";
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View RootView= inflater.inflate(R.layout.pendingorders, container, false);
listView1 = (ListView) RootView.findViewById(R.id.listview);
return RootView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference();
FirebaseUser user = firebaseAuth.getCurrentUser();
userId = user.getUid();
}
#Override
public void onStart() {
super.onStart();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ServiceConsumer uInfo = new ServiceConsumer();
uInfo.setPkgDetail(ds.child(userId).getValue(ServiceConsumer.class).getPkgDetail());
uInfo.setPkgWeight(ds.child(userId).getValue(ServiceConsumer.class).getPkgWeight());
uInfo.setPersonContct(ds.child(userId).getValue(ServiceConsumer.class).getPersonContct());
uInfo.setPickupAddrs(ds.child(userId).getValue(ServiceConsumer.class).getPickupAddrs());
uInfo.setConsumerName(ds.child(userId).getValue(ServiceConsumer.class).getConsumerName());
uInfo.setConsumerPhone(ds.child(userId).getValue(ServiceConsumer.class).getConsumerPhone());
uInfo.setConsumerAddres(ds.child(userId).getValue(ServiceConsumer.class).getConsumerAddres());
Log.d(TAG, "showData:pkgdetail:" + uInfo.getPkgDetail());
Log.d(TAG, "showData:pkgweight:" + uInfo.getPkgWeight());
Log.d(TAG, "showData:persncntct:"+uInfo.getPersonContct());
Log.d(TAG, "showData:pickup:"+uInfo.getPickupAddrs());
Log.d(TAG, "showData:cnname:"+uInfo.getConsumerName());
Log.d(TAG, "showData:cnphone:"+uInfo.getConsumerPhone());
Log.d(TAG, "showData:cnadd:"+uInfo.getConsumerAddres());
ArrayList<String>array= new ArrayList<>();
array.add(uInfo.getPkgDetail());
array.add(uInfo.getPkgWeight());
array.add(uInfo.getPersonContct());
array.add(uInfo.getPickupAddrs());
array.add(uInfo.getConsumerName());
array.add(uInfo.getConsumerAddres());
array.add(uInfo.getConsumerPhone());
ArrayAdapter<String> adapter= new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,array);
listView1.setAdapter(adapter);
}
}
ServiceConsumer class
public class ServiceConsumer {
private String Id;
private String PkgDetail;
private String PkgWeight;
private String PersonContct;
private String PickupAddrs;
private String ConsumerName;
private String ConsumerPhone;
private String ConsumerAddres;
public ServiceConsumer() {
}
public ServiceConsumer(String id, String pkgdetail, String pkgweight, String personContct, String add, String consumerName, String consumerPhone, String consumerAdd) {
Id= id;
PkgDetail = pkgdetail;
PkgWeight = pkgweight;
PersonContct = personContct;
PickupAddrs = add;
ConsumerName = consumerName;
ConsumerPhone = consumerPhone;
ConsumerAddres = consumerAdd;
}
public String getId() {
return Id;
}
public String getPkgDetail() {
return PkgDetail;
}
public String getPkgWeight() {
return PkgWeight;
}
public String getPersonContct() {
return PersonContct;
}
public String getPickupAddrs() {
return PickupAddrs;
}
public String getConsumerName() {
return ConsumerName;
}
public String getConsumerPhone() {
return ConsumerPhone;
}
public String getConsumerAddres() {
return ConsumerAddres;
}
public void setId(String id) {
Id = id;
}
public void setPkgDetail(String pkgDetail) {
PkgDetail = pkgDetail;
}
public void setPkgWeight(String pkgWeight) {
PkgWeight = pkgWeight;
}
public void setPersonContct(String personContct) {
PersonContct = personContct;
}
public void setPickupAddrs(String pickupAddrs) {
PickupAddrs = pickupAddrs;
}
public void setConsumerName(String consumerName) {
ConsumerName = consumerName;
}
public void setConsumerPhone(String consumerPhone) {
ConsumerPhone = consumerPhone;
}
public void setConsumerAddres(String consumerAddres) {
ConsumerAddres = consumerAddres;
}
}

Try to make PkgDetail NonNull or save an empty string to it.
private String PkgDetail = "" ;

Related

Unable to Get Images to Display in Recycler View- Text is Sucessfully Displayed

Please see the following issue:
All User Profile Images are not successfully displaying in the RecyclerView.
Text view is successfully displaying in the RecyclerView.
I looked up other similar issues online, but have not been able to find a solution.
I have updated my google play services, and my Firebase storage dependencies.
I am able to successfully pull the current user profile image in another activity.
I am getting the following 404 error message below:
**Adapter**
public class FindFriendsAdapter extends RecyclerView.Adapter<FindFriendsAdapter.FindFriendsViewHolder>
{
private Context context;
private List<FindFriendModel> findFriendModelList;
////This is a constructor and is a must have for recyclerviews/////
public FindFriendsAdapter(Context context, List<FindFriendModel> findFriendModelList) {
this.context = context;
this.findFriendModelList = findFriendModelList;
}
////This is a constructor and is a must have for recyclerviews/////
#NonNull
#Override
public FindFriendsAdapter.FindFriendsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.find_friends_layout, parent, false);
return new FindFriendsViewHolder(view); ///// layout converts our xml layout file to a programmable file some kind of way.
}
#Override
public void onBindViewHolder(#NonNull FindFriendsAdapter.FindFriendsViewHolder holder, int position) {
final FindFriendModel friendModel = findFriendModelList.get(position);
holder.text_view_full_name.setText(friendModel.getFull_name());
StorageReference fileref = FirebaseStorage.getInstance().getReference().child(Constants.IMAGES_FOLDER +"/" + friendModel.getProfileimage());
fileref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Glide.with(context)
.load(uri)
.placeholder(R.drawable.small_grey_circle)
.error(R.drawable.small_grey_circle)
.into(holder.imageView_profile);
}
});
}
#Override
public int getItemCount() {
return findFriendModelList.size();
}
public class FindFriendsViewHolder extends RecyclerView.ViewHolder{
private CircleImageView imageView_profile;
private TextView text_view_full_name;
private ImageButton button_request, button_cancel_request;
public FindFriendsViewHolder(#NonNull View itemView) {
super(itemView);
imageView_profile = itemView.findViewById(R.id.find_friends_profile_picture);
text_view_full_name = itemView.findViewById(R.id.find_friends_user_full_name);
button_request = itemView.findViewById(R.id.button_send_requests);
button_cancel_request = itemView.findViewById(R.id.button_cancel_requests);
}
}
}
**Model Class**
public class FindFriendModel
{
private String full_name;
private String profileimage;
private String userID;
private boolean requestSent;
public FindFriendModel(String full_name, String profileimage, String userID, boolean requestSent) {
this.full_name= full_name;
this.profileimage = profileimage;
this.userID = userID;
this.requestSent = requestSent;
}
public FindFriendModel() {}
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getProfileimage() {
return profileimage;
}
public void setProfileimage(String profileimage) {
this.profileimage = profileimage;
}
public String getUserID() {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
public boolean isRequestSent() {
return requestSent;
}
public void setRequestSent(boolean requestSent) {
this.requestSent = requestSent;
}
}
**Fragment Java Class**
public class FindFriendsFragment extends Fragment {
private RecyclerView recycler_view_find_friends;
private FindFriendsAdapter findFriendsAdapter;
private List<FindFriendModel> findFriendModelList;
private TextView text_view_empty_Friends_List;
private DatabaseReference databaseReference;
private FirebaseUser currentUser;
public FindFriendsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_find_friends, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recycler_view_find_friends = view.findViewById(R.id.recycler_view_find_friends);
text_view_empty_Friends_List = view.findViewById(R.id.text_view_empty_find_friends);
recycler_view_find_friends.setLayoutManager(new LinearLayoutManager(getActivity()));
findFriendModelList = new ArrayList<>();
findFriendsAdapter = new FindFriendsAdapter(getActivity(), findFriendModelList);
recycler_view_find_friends.setAdapter(findFriendsAdapter);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
currentUser = FirebaseAuth.getInstance().getCurrentUser();
text_view_empty_Friends_List.setVisibility(View.VISIBLE);
Query query = databaseReference.orderByChild("full_name");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
findFriendModelList.clear();
for (final DataSnapshot ds : dataSnapshot.getChildren())
{
final String userID = ds.getKey();
if (userID.equals(currentUser.getUid()))
return;
if (ds.child("full_name").getValue()!=null)
{
String fullName = ds.child("full_name").getValue().toString();
String profileImage = ds.child("profileimage").getValue().toString();
findFriendModelList.add(new FindFriendModel(fullName, profileImage, userID, false));
findFriendsAdapter.notifyDataSetChanged();
text_view_empty_Friends_List.setVisibility(View.GONE);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(),"Failed to fetch friends", Toast.LENGTH_SHORT).show();
}
});
}
}
````
ds.child("full_name").getValue()!=null should be replaced by
Objects.equals(ds.child("full_name"), null)
It worked for me when I had the same error, maybe it will help you as well !
Figured out the issue:
The issue was that I was already saving my images images to Firebase Storage, and I was trying to get the download url string again.
I fixed the following part of my adapter:
#Override
public void onBindViewHolder(#NonNull FindFriendsAdapter.FindFriendsViewHolder holder, int position) {
final FindFriendModel friendModel = findFriendModelList.get(position);
holder.text_view_full_name.setText(friendModel.getFull_name());
Glide.with(context)
.load(friendModel.getProfileimage())
.placeholder(R.drawable.small_grey_circle)
.error(R.drawable.small_grey_circle)
.into(holder.imageView_profile);
}

how to retrieve all data from firebase and display on listview android?

I am making an android app ,which is get order from customers,but i faced a problem . I am trying to Retrieve Data from Firebase and display in a list view. I can get the data back from Firebase but when it displays in the listview it just displays one data in many times. I want to be displayed on one line for each record. Can anyone see where i am going wrong??
Database Image
ListView Image
OrderHistory
public class OrderHistory
{
String ammount,photoId,trxId,name,copy,photoSize,date;
public OrderHistory(String name,String photoId,String trxId,String copy,String photoSize,String ammount,String date)
{
this.name = name;
this.ammount = ammount;
this.photoId = photoId;
this.copy = copy;
this.photoSize = photoSize;
this.trxId = trxId;
this.date = date;
}
public String getAmmount() {
return ammount;
}
public void setAmmount(String ammount) {
this.ammount = ammount;
}
public String getPhotoId() {
return photoId;
}
public void setPhotoId(String photoId) {
this.photoId = photoId;
}
public String getTrxId() {
return trxId;
}
public void setTrxId(String trxId) {
this.trxId = trxId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCopy() {
return copy;
}
public void setCopy(String copy) {
this.copy = copy;
}
public String getPhotoSize() {
return photoSize;
}
public void setPhotoSize(String photoSize) {
this.photoSize = photoSize;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
OrderHistoryAdapter
public class OrderHistoryAdapter extends BaseAdapter {
private List<OrderHistory> orderHistories;
Context context;
public OrderHistoryAdapter(Context context, List<OrderHistory> myOrderInformations) {
this.context = context;
this.orderHistories = myOrderInformations;
}
#Override
public int getCount() {
return orderHistories.size();
}
#Override
public Object getItem(int position) {
return orderHistories.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.show_my_order_history, parent, false);
final TextView txtName, txtdate, txtPhotoId, trxId,txtAmount,txtPhotoSize,txtCopy;
txtName = (TextView)view.findViewById(R.id.txtName);
txtdate = (TextView)view.findViewById(R.id.txtDate);
txtPhotoId = (TextView)view.findViewById(R.id.txtPhotoId);
trxId = (TextView)view.findViewById(R.id.txtTrx);
txtAmount = (TextView)view.findViewById(R.id.txtAmount);
txtPhotoSize = (TextView)view.findViewById(R.id.txtSize);
txtCopy = (TextView)view.findViewById(R.id.txtCopy);
txtName.setText(orderHistories.get(position).getName());
txtdate.setText(orderHistories.get(position).getDate());
txtPhotoId.setText(orderHistories.get(position).getPhotoId());
trxId.setText(orderHistories.get(position).getTrxId());
txtAmount.setText(orderHistories.get(position).getAmmount());
txtCopy.setText(orderHistories.get(position).getCopy());
txtPhotoSize.setText(orderHistories.get(position).getPhotoSize());
return view;
}
}
OrderHistoryList
public class OrderHistoryList extends AppCompatActivity
{
private DatabaseReference databaseReference;
private List<OrderHistory> orderHistories;
private static String phoneNumber;
private ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_my_order);
Firebase.setAndroidContext(this);
listView = (ListView)findViewById(R.id.listView);
getAllOrderFromFirebase();
}
private void getAllOrderFromFirebase()
{
orderHistories = new ArrayList<>();
databaseReference = FirebaseDatabase.getInstance().getReference("order");
String phone = getIntent().getExtras().getString("phone");
databaseReference.orderByChild("phone").equalTo(phone).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String amount, photoId, trxId, name, copy, photoSize, date;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
name = snapshot.child("name").getValue(String.class);
photoId = snapshot.child("photoId").getValue(String.class);
amount = snapshot.child("totalAmount").getValue(String.class);
trxId = snapshot.child("trxId").getValue(String.class);
photoSize = snapshot.child("photoSize").getValue(String.class);
date = snapshot.child("date").getValue(String.class);
copy = snapshot.child("totalCopy").getValue(String.class);
orderHistories.add(new OrderHistory(name, photoId, trxId, copy, photoSize, amount, date));
}
OrderHistoryAdapter adapter;
adapter = new OrderHistoryAdapter(OrderHistoryList.this, orderHistories);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
I guess your problem is by the way you refer to your data so instead of this
databaseReference = FirebaseDatabase.getInstance().getReference("order");
use this
databaseReference = FirebaseDatabase.getInstance().getReference().child("order");
and you didn't use a query object to query your database reference
so now you don't query directly from databaseReference like the way you did it
instead you do this:
Query query=databaseReference.orderByChild("phone").equalTo(phone);
once you have a query that fits you now add on child listener and continue the rest of your code:
query.addChildEventListener(new ChildEventListener() {
//the rest of your code goes here(on child added/changed/......)
)};

Attempt to invoke virtual method on a null object reference - Firebase database android

I am trying to read the 'resName' and 'status' values from PjSxhQXCyXdSv07LxVzU7buvhkF2 under business_info node from firebase database, as seen .
I keep getting this error:
Attempt to invoke virtual method 'java.lang.String com.example.android.project_water.Utilities.RestaurantInformation.getResName()' on a null object reference.
Does anyone know how to solve this? Please let me know if more info is needed.
Code:
public class Info extends Fragment {
private DatabaseReference mDatabase;
private FirebaseAuth firebaseAuth;
private String businessID;
private TextView resNameChange, statusChange;
public Info() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_info, container, false);
SharedPreferences businessID1 = getActivity().getSharedPreferences("BUSINESS_ID", Context.MODE_PRIVATE);
businessID = businessID1.getString("businessID", "businessIDNotFound");
Log.i("BUSINESS KEY IS: ", businessID);
firebaseAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
resNameChange = rootView.findViewById(R.id.resNameChange);
statusChange = rootView.findViewById(R.id.statusChange);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
return rootView;
}
public void showData(DataSnapshot dataSnapshot) {
if (dataSnapshot.child("business_info").child(businessID).exists()) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
RestaurantInformation resInfo = new RestaurantInformation();
//error on the line below******
resInfo.setResName(ds.child(businessID).getValue(RestaurantInformation.class).getResName());
resInfo.setStatus(ds.child(businessID).getValue(RestaurantInformation.class).getStatus());
resNameChange.setText(resInfo.getResName());
statusChange.setText(resInfo.getStatus());
}
} else {
resNameChange.setText("NAME");
statusChange.setText("ONLINE");
}
}
}
My Model
public class RestaurantInformation {
private String resName;
private String status;
public RestaurantInformation() {
}
public RestaurantInformation(String resName) {
this.resName = resName;
}
public RestaurantInformation(String resName, String status) {
this.resName = resName;
this.status = status;
}
public String getResName() {
return resName;
}
public void setResName(String resName) {
this.resName = resName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Your current code is downloading the entire database and then tries to figure out what to show client-side. That is a very wasteful use of your user's bandwidth. I recommend only listening for the business you're interested in:
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("business_info").child(businessID).addValueEventListener(new ValueEventListener() {
Then you can simplify your showData method to:
public void showData(DataSnapshot snapshot) {
if (snapshot.exists()) {
RestaurantInformation resInfo = snapshot.getValue(RestaurantInformation.class)
resNameChange.setText(resInfo.getResName());
statusChange.setText(resInfo.getStatus());
} else {
resNameChange.setText("NAME");
statusChange.setText("ONLINE");
}
}

Android Firebase - databaseException with model class

what can be the reason that firebase gives databaseException error? I am new to android firebase adapter and I am facing an issue of databaseException. I was trying to get adapter in MainCommentFragment so I can use viewPager and recyclerview. But it seems like there is an error when I call mRecyclerView.setAdapter(mCommentAdapter); in MainCommentFragment.java. Can anyone help me with this?
Comment.java
public class Comment
{
public String uid;
public String username;
public String body;
public String time;
public String choice;
public int likeCount;
public int dislikeCount;
public Map<String, Boolean> likes = new HashMap<>();
public Map<String, Boolean> dislikes = new HashMap<>();
public Comment()
{
}
public Comment(String uid, String username, String body, String time, String choice)
{
this.uid = uid;
this.username = username;
this.body = body;
this.time = time;
this.choice = choice;
}
public Map<String, Object> toMap()
{
HashMap<String, Object> result = new HashMap<>();
result.put("uid", uid);
result.put("username", username);
result.put("time", time);
result.put("body", body);
result.put("likeCount", likeCount);
result.put("dislikeCount", dislikeCount);
result.put("likes", likes);
result.put("dislikes", dislikes);
result.put("choice", choice);
return result;
}
}
MainCommentFragment.java
public abstract class MainCommentFragment extends Fragment
{
/*UI*/
private RecyclerView mRecyclerView; //declaring recycler view
/*Firebase*/
private DatabaseReference mDatabase; //declaring database
/*Other*/
private FirebaseRecyclerAdapter<Comment, CommentViewHolder> mCommentAdapter; //declaring adapter for post
private LinearLayoutManager mLinearLayoutManager; //declaring linear layout manager
private String postKey;
/*Function*/
public MainCommentFragment() //creating a constructor for MainFragment
{
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) //when view is created
{
super.onCreateView(inflater, container, savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment_comment, container, false); //fragment_all_posts will invoked
mDatabase = FirebaseDatabase.getInstance().getReference(); //initializing database
mRecyclerView = (RecyclerView)rootView.findViewById(R.id.fragment_comment_recycler_view); //initializing recycler view
mRecyclerView.setHasFixedSize(true); //giving fixed size property to recycler view
RoomActivity roomActivity = (RoomActivity)getActivity();
postKey = roomActivity.getPostKey();
System.out.println("postKey=============================" + postKey);
return rootView; //returning view
}
#Override
public void onActivityCreated(Bundle savedInstanceState) //when activity is created
{
super.onActivityCreated(savedInstanceState);
mLinearLayoutManager = new LinearLayoutManager(getActivity()); //initializing linear layout manager
mLinearLayoutManager.setReverseLayout(true); //make the layout reverse
mLinearLayoutManager.setStackFromEnd(true); //make the layout stack from end
mRecyclerView.setLayoutManager(mLinearLayoutManager); //initialize recycler view
Query commentQuery = getQuery(mDatabase, postKey); //get query for database
mCommentAdapter = new FirebaseRecyclerAdapter<Comment, CommentViewHolder>(Comment.class, R.layout.comment_item, CommentViewHolder.class, commentQuery) //initializing post adapter
{
#Override
protected void populateViewHolder(CommentViewHolder viewHolder, Comment model, int position)
{
viewHolder.bindToComment(model, new View.OnClickListener()
{
#Override
public void onClick(View v)
{
DatabaseReference globalCommentRef = mDatabase.child("Comment").child(postKey);
onLikeClicked(globalCommentRef);
switch(v.getId())
{
case R.id.comment_item_like_btn:
onLikeClicked(globalCommentRef);
break;
case R.id.comment_item_dislike_btn:
onDislikeClicked(globalCommentRef);
break;
}
}
});
}
};
mRecyclerView.setAdapter(mCommentAdapter); //recycler view will not display post adapter
}
private void onLikeClicked(DatabaseReference commentRef)
{
commentRef.runTransaction(new Transaction.Handler()
{
#Override
public Transaction.Result doTransaction(MutableData mutableData)
{
Comment c = mutableData.getValue(Comment.class);
if(c == null)
{
return Transaction.success(mutableData);
}
if(c.likes.containsKey(FirebaseAuth.getInstance().getCurrentUser().getUid()))
{
} else
{
c.likeCount = c.likeCount + 1;
c.likes.put(FirebaseAuth.getInstance().getCurrentUser().getUid(), true);
if(c.dislikeCount != 0)
{
c.dislikeCount = c.dislikeCount - 1;
c.dislikes.remove(FirebaseAuth.getInstance().getCurrentUser().getUid());
}
}
mutableData.setValue(c);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot)
{
}
});
}
private void onDislikeClicked(DatabaseReference commentRef)
{
commentRef.runTransaction(new Transaction.Handler()
{
#Override
public Transaction.Result doTransaction(MutableData mutableData)
{
Comment c = mutableData.getValue(Comment.class);
if(c == null)
{
return Transaction.success(mutableData);
}
if(c.dislikes.containsKey(FirebaseAuth.getInstance().getCurrentUser().getUid()))
{
} else
{
c.dislikeCount = c.dislikeCount + 1;
c.dislikes.put(FirebaseAuth.getInstance().getCurrentUser().getUid(), true);
if(c.likeCount != 0)
{
c.likeCount = c.likeCount - 1;
c.likes.remove(FirebaseAuth.getInstance().getCurrentUser().getUid());
}
}
mutableData.setValue(c);
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot)
{
}
});
}
public abstract Query getQuery(DatabaseReference databaseReference, String postKey); //declaring query
}
This is the error message.
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.Long to type packagename.Comment

Retrieving data to listview

I've been trying to get the Firebase data to appear in the ListView, but I can not. The list returns, but in the wrong way
Could someone help me, please?
Thanks a lot!
Here is Ideia class:
public class Ideia {
private String distrito, clube, nomeCompleto, nomeIdeia, descricaoIdeia;
public Ideia(){}
public String getDistrito() {
return distrito;
}
public void setDistrito(String distrito) {
this.distrito = distrito;
}
public String getClube() {
return clube;
}
public void setClube(String clube) {
this.clube = clube;
}
public String getNomeCompleto() {
return nomeCompleto;
}
public void setNomeCompleto(String nomeCompleto) {
this.nomeCompleto = nomeCompleto;
}
public String getNomeIdeia() {
return nomeIdeia;
}
public void setNomeIdeia(String nomeIdeia) {
this.nomeIdeia = nomeIdeia;
}
public String getDescricaoIdeia() {
return descricaoIdeia;
}
public void setDescricaoIdeia(String descricaoIdeia) {
this.descricaoIdeia = descricaoIdeia;
}
}
Here MyIdeaActivity:
public class MyIdeaActivity extends AppCompatActivity {
private static final String TAG = "PostDetailActivity";
private ListView mListView;
private Button mBtnMenu;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference mDatabaseRef;
private List<Ideia> mList;
private ArrayAdapter mListAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_idea_activity);
firebaseDatabase = FirebaseDatabase.getInstance();
mDatabaseRef = firebaseDatabase.getReference();
mListView = (ListView) findViewById(R.id.lv_my_idea_myidea);
mBtnMenu = (Button) findViewById(R.id.btn_menu_myidea);
mList = new ArrayList<>();
mListAdapter = new ArrayAdapter<Ideia>(this, android.R.layout.simple_dropdown_item_1line, mList);
mListView.setAdapter(mListAdapter);
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data : dataSnapshot.getChildren()) {
Ideia i = data.getValue(Ideia.class);
mList.add(i);
mListAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Just Override toString() Method in Ideia class
public class Ideia {
private String distrito, clube, nomeCompleto, nomeIdeia, descricaoIdeia;
public Ideia(){}
public String getDistrito() {
return distrito;
}
public void setDistrito(String distrito) {
this.distrito = distrito;
}
public String getClube() {
return clube;
}
public void setClube(String clube) {
this.clube = clube;
}
public String getNomeCompleto() {
return nomeCompleto;
}
public void setNomeCompleto(String nomeCompleto) {
this.nomeCompleto = nomeCompleto;
}
public String getNomeIdeia() {
return nomeIdeia;
}
public void setNomeIdeia(String nomeIdeia) {
this.nomeIdeia = nomeIdeia;
}
public String getDescricaoIdeia() {
return descricaoIdeia;
}
public void setDescricaoIdeia(String descricaoIdeia) {
this.descricaoIdeia = descricaoIdeia;
}
#Override
public String toString() {
return distrito; // set field here which you want to display in list
}
}
When you are working with firebase, It is good practice to use firebase UI So in your case If you have to display list then you can use firebase ListAdapter or firebase Recyclerview adapter for it. It's designed for firebase it manages very efficiently.
Follow this code for firebase Recyclerview Adapter it helps you
Firebase with ListView and Recyclerview

Categories

Resources