Firebase list child in listview - android

I'm new to Firebase, and I need to show a child info on a listview. It adds the data, but it does not show on listview and the app crashes. No error is shown on log, but on firebase crash I have this error:
Exception com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String
com.google.android.gms.internal.zzamy.zzcg ()
com.google.android.gms.internal.zzamy.zzb ()
com.google.android.gms.internal.zzamy.zza ()
com.google.firebase.database.DataSnapshot.getValue ()
br.com.imobapp.CorretorFragment$1.onChildAdded (CorretorFragment.java:58)
com.google.android.gms.internal.zzaip.zza ()
com.google.android.gms.internal.zzakp.zzcxi ()
com.google.android.gms.internal.zzaks$1.run ()
android.os.Handler.handleCallback (Handler.java:739)
android.os.Handler.dispatchMessage (Handler.java:95)
android.os.Looper.loop (Looper.java:145)
android.app.ActivityThread.main (ActivityThread.java:5832)
My data is like this (Sorry, can't post pics since my account is new, only the link):
https://i.stack.imgur.com/lZHFC.jpg
My model is:
import com.google.firebase.database.IgnoreExtraProperties;
#IgnoreExtraProperties
public class ModelCorretor {
private String CorNome;
private String CorCreci;
public ModelCorretor(){
};
public ModelCorretor(String CorNome, String CorCreci){
this.CorNome = CorNome;
this.CorCreci = CorCreci;
};
public String getCorNome() {
return CorNome;
}
public void setCorNome(String corNome) {
CorNome = corNome;
}
public String getCorCreci() {
return CorCreci;
}
public void setCorCreci(String corCreci) {
CorCreci = corCreci;
}
}
And my fragment for showing it on listview:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import static android.content.ContentValues.TAG;
public class CorretorFragment extends Fragment implements View.OnClickListener {
public CorretorFragment() {
// Required empty public constructor
}
ImageButton btAddCor, btSearchCor;
ListView lvCorretor;
DatabaseReference dref;
ArrayList<String> list = new ArrayList<>();
ArrayAdapter<String> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_corretor, container, false);
btAddCor =(ImageButton)view.findViewById(R.id.btAddCor);
btAddCor.setOnClickListener(this);
btSearchCor =(ImageButton)view.findViewById(R.id.btSearchCor);
btSearchCor.setOnClickListener(this);
lvCorretor = (ListView)view.findViewById(R.id.lvCorretor);
adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_dropdown_item_1line, list);
lvCorretor.setAdapter(adapter);
dref = FirebaseDatabase.getInstance().getReference().child("Corretores");
dref.addChildEventListener(new ChildEventListener() {
#Override
// Read from the database
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String value = dataSnapshot.getValue(String.class);
list.add(value);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
list.remove(value);
adapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
return view;
}
#Override
public void onClick(View view){
MainActivity activity = (MainActivity)getActivity();
switch(view.getId()){
case R.id.btAddCor:
activity.chamaAddCor();
break;
case R.id.btSearchCor:
activity.chamaSearchCor();
break;
default: throw new RuntimeException("unreachable");
}
}
}
If any more code is needed or if I did something wrong in the question, please let me know.
I have an idea that I have to set a child for it to show, like I did in FirebaseDatabase.getInstance().getReference().child("Corretores"); but I tried a lot and have no clue how to do it on the onChildAdded.

The issue is here:
String value = dataSnapshot.getValue(String.class);
You shouldn't be getting a String object, you should be getting the model for the object you want. You have a model for your Corretor, so you do:
ModelCorretor value = dataSnapshot.getValue(ModelCorretor.class);
getValue returns a hashmap and you are assigning it to a string, which is why you are getting that error. Firebase is great in that it will build that object for you by just inserting the ModelCorretor as a parameter in the getValue method.

Related

android studio recyclerView with firestore

I have orders collection in firestore:
And I have Sellers collection and inside Sellers collection have another Fruits collection :
I want to get data in orders collection only orders collection fruit_ID equals Sellers/Fruits collection Document ID and add into recyclerview
Is it possible?
Activity class:
package com.example.freshbucket.Seller;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.widget.Toast;
import com.example.freshbucket.Adapter.OrdersSellerRecylerAdapter;
import com.example.freshbucket.Model.PlaceOrder;
import com.example.freshbucket.R;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import javax.annotation.Nullable;
import static android.support.constraint.Constraints.TAG;
public class SellerGetOrdersActivity extends AppCompatActivity {
String fid, pro;
private FirebaseAuth mAuth = FirebaseAuth.getInstance();
String user_id = mAuth.getCurrentUser().getUid();
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference orders = db.collection("Orders");
private CollectionReference sellers = db.collection("Sellers/"+user_id+"/Fruits");
private OrdersSellerRecylerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seller_get_orders);
setupRecyclerView();
}
private void setupRecyclerView()
{
Query query =orders.orderBy("timestamp", Query.Direction.DESCENDING).whereEqualTo("fruit_ID",fid);
FirestoreRecyclerOptions<PlaceOrder> options = new FirestoreRecyclerOptions.Builder<PlaceOrder>().setQuery(query, PlaceOrder.class).build();
adapter = new OrdersSellerRecylerAdapter(options);
RecyclerView recyclerView = findViewById(R.id.ordersReView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
//swipe delete
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT| ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder viewHolder1) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
adapter.deleteItem(viewHolder.getAdapterPosition());
}
}).attachToRecyclerView(recyclerView);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
sellers.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.d(TAG, "Error:" + e.getMessage());
} else {
for (DocumentSnapshot doc :queryDocumentSnapshots){
fid = doc.getId();
// pro = doc.getString("province");
// fid = doc.getString("fruit_ID");
Toast.makeText(SellerGetOrdersActivity.this, "Register error:" +fid , Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Adapter:
package com.example.freshbucket.Adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.example.freshbucket.Model.PlaceOrder;
import com.example.freshbucket.R;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
public class OrdersSellerRecylerAdapter extends FirestoreRecyclerAdapter<PlaceOrder, OrdersSellerRecylerAdapter.OrdersSellerHolder> {
Context context;
public OrdersSellerRecylerAdapter(#NonNull FirestoreRecyclerOptions<PlaceOrder> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull final OrdersSellerHolder holder, int position, #NonNull final PlaceOrder model) {
holder.txtfruitname.setText(model.getName());
holder.txtqun.setText(model.getQun());
holder.txtcusname.setText(model.getCustomer_Name());
holder.txtaddress1.setText(model.getAddressLine1());
holder.txtaddress2.setText(model.getAddressLine2());
holder.txtcity.setText(model.getCity());
}
#NonNull
#Override
public OrdersSellerHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.order_list_item_seller,viewGroup, false);
context = viewGroup.getContext();
return new OrdersSellerHolder(v);
}
class OrdersSellerHolder extends RecyclerView.ViewHolder{
TextView txtfruitname, txtqun, txtcusname, txtaddress1, txtaddress2, txtcity;
EditText tctBprice;
public OrdersSellerHolder(#NonNull View itemView) {
super(itemView);
txtfruitname = itemView.findViewById(R.id.fruitnametext);
txtqun = itemView.findViewById(R.id.fruitquntext);
txtcusname = itemView.findViewById(R.id.cusnametext);
txtaddress1 = itemView.findViewById(R.id.addres1text);
txtaddress2 = itemView.findViewById(R.id.addres2text);
txtcity = itemView.findViewById(R.id.citytext);
}
}
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
}
I want to get data in orders collection only orders collection
fruit_ID
OK, you want to get fruit_ID?
equals Sellers/Fruits collection Document ID and add into recyclerview
and you want to get fruit_ID, which equals with Sellers/Fruits ?
like if (fruit_ID.equals(sellerFruits_ID) {// get fruit_ID}
I will try to answer it.
PROBLEM
1. you as a seller and have your seller uid in your Sellers collection and want to get V4x1Dh..
2. You have buyer uid in your Orders collection and want to get 83Fmf..
3. You want to get Banana in Sellers/Fruits, which the Banana as id.
Lastly, you want to load datas of Sellers/Fruits into recyclerView because
you want to get data in orders collection only orders collection
fruit_ID
ANSWER
Answer number one: Please retrieve the Sellers ids and get V4x1Dh based ViewHolder position that I will explain later.
Answer number two: Please retrieve the Orders ids and get 83Fmf based ViewHolder position that I will explain later.
Answer number two: Please retrieve the Sellers Fruits ids let's say sellerFruit_ID and get Banana based ViewHolder position that I will explain later. NOTE: Since Banana in document it will be id.
DETAILS:
Retrieving the Sellers ids and get V4x1Dh:
firebaseFirestore
.collection("Sellers")
.addSnapshotListener(new EventListener<QuerySnapshot>(){
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e){
for (DocumentChange doc : documentSnapshots.getDocumentChanges()){
if (doc.getType() == DocumentChange.Type.ADDED){
// RETRIEVING Orders id
String orders_ID = doc.getDocument().getId();
YourContentOrdersHere contentOrders = doc.getDocument().toObject(YourContentOrdersHere.class).withId(orders_ID);
// RETRIEVING Sellers id
String sellers_ID = doc.getDocument().getId();
YourContentSellersHere contentSellers = doc.getDocument().toObject(YourContentSellersHere.class).withId(sellers_ID);
contentListOrders.add(contentOrders); //example: List<YourContentOrdersHere> contentList
adapter.notifyDataSetChanged(); // before of course, you add this in onCreate adapterOrders = new YourAdapterOrders(contentListOrders);
contentListSellers.add(contents); //example: List<YourContentSellersHere> contentList
adapter.notifyDataSetChanged(); // before of course, you add this in onCreate adapterSellers = new YourAdapterSellers(contentListSellers);
}
}
}
});
make sure your content class extends the ids
public class YourContentOrdersHere extends OrdersId {
// make your constructor here of course
// make your getter to get id
}
and make OrdersId.class
public class OrdersId{
#Exclude
public String OrdersId;
public <T extends OrdersId> T withId(#NonNull final String id) {
this.OrdersId = id;
return (T) this;
}
}
and last one , from your adapter class retrieving OrdersId. As Example:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// GET YOUR `Sellers` id based position and getSellerId() from getter of your content class
String sellers_ID = contentListSeller.get(position).getSellerId(); // don't forget List<YourContentSellers> contentList = new ArrayList<>();
firebaseFirestore
.collection("Sellers")
.document(sellers_ID)
.collection("Fruits")
.document("Banana")
// STORE 'LIKE TAP' USING LIKE BUTTON
holder.likeHome.seOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
/* RETRIEVING VALUE UNDER currentUserId */
firebaseFirestore.collection("Posts/" + postId + "/Likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>(){
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task){
if (!task.getResult().exists()) {
/* STORE NEW VALUE */
Map<String, Object> likesMap = new HashMap<>();
likesMap.put("timestamp", FieldValue.serverTimestamp);
firebaseFirestore.collection("Posts/" + postId + "/Likes").document(currentUserId).set(likesMap);
} else {
// retrieve like timestamp
String whenToLike = task.getResult().getString("timestamp");
holder.setWhenToLike(whenToLike);
/* DELETE VALUE */
firebaseFirestore.collection("Posts/" + postId + "/Likes").document(currentUserId).delete();
}
}
});
}
});
}

Stuck with this issue of eventlistener with list

Have been trying to solve this problem for so long
I have a list called datalist in which I am storing data from firebase in order to use it in the recyclerview.
But the problem is inside childeventlistener the list is getting updated but before this happens return call is made and it ends up in a null list.
What should be done?
package com.example.dell.hungryapp;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Dell on 5/29/2017.
*/
public class itemmodel {
public String item_name;
public int quantity;
public String getItem_name() {
return item_name;
}
public void setItem_name(String item_name) {
this.item_name = item_name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public static List<itemmodel> getObjectList(){
final List<itemmodel> datalist=new ArrayList<>();
DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
databaseReference.child("Users").child(user.getUid()).child("Inventory").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println("value is : "+dataSnapshot.getValue());
String id=dataSnapshot.getKey();
Integer qty=dataSnapshot.getValue(Integer.class);
itemmodel item=new itemmodel();
item.setItem_name(id);
item.setQuantity(qty);
datalist.add(item);
System.out.println("before size : "+datalist.size());
}
#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) {
}
});
System.out.println("before size : "+datalist.size());
return datalist;
}
}
Kindly follow this link if you want to retrieve the whole data from inventory. I have used maps in order to retrieve the whole data and stored it in array list
final DatabaseReference myRef = database.getReference().child("users").child(users.getUid).child("Inventory");
Remove the previous markers as the location updates
Hope it solves your problem

Firebase Database Exception [duplicate]

This question already has an answer here:
android save object in firebase
(1 answer)
Closed 5 years ago.
Here is the class where i intend to read a Location type data item from firebase database and store it in a Location type Object. I even tried to store the datasnapshot in an object of the class that had a Location type argument in the constructor, i got the same error saying :
" com.google.firebase.database.DatabaseException: Class android.location.Location is missing a constructor with no arguments"
package com.example.aadi.sarthi_;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class ActiveNotifications extends Fragment{
public static final String NOTIFICATION_MSG = "NOTIFICATION MSG";
public RecyclerView recyclerView;
String user_mac;
public List<notifyListRowItem> result;
public UserAdapter userAdapter;
private DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
private DatabaseReference eventRef = reference.child("Events");
// Create a Intent send by the notification
public static Intent makeNotificationIntent(Context context, String msg) {
Intent intent = new Intent( context, ActiveNotifications.class );
intent.putExtra( NOTIFICATION_MSG, msg );
return intent;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_active_notifications, container, false);
getMac();
result = new ArrayList<>();
recyclerView = (RecyclerView) view.findViewById(R.id.notification_list);
recyclerView.setHasFixedSize(true);
LinearLayoutManager rlm = new LinearLayoutManager(getActivity());
rlm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(rlm);
/*
createNotifyListRowItem();*/
userAdapter = new UserAdapter(result);
recyclerView.setAdapter(userAdapter);
updateList();
return view;
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()){
case 0:
break;
case 1:
break;
}
return super.onContextItemSelected(item);
}
public void updateList(){
final DatabaseReference locationRef = reference.child(String.valueOf(user_mac)).child("location");
final Location userLoc = null;
final Location eventLoc = null;
locationRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Location location = dataSnapshot.getValue(Location.class);
userLoc.set(location);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
eventRef.limitToFirst(2).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
eventRef.push().child("location");
Location location = dataSnapshot.getValue(Location.class);
eventLoc.set(location);
if(eventLoc.distanceTo(userLoc)<=1000) {
result.add(dataSnapshot.getValue(notifyListRowItem.class));
userAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Log.w("asd", "In onChildChanged");
notifyListRowItem notifyListRowItem = dataSnapshot.getValue(notifyListRowItem.class);
int index = getItemIndex(notifyListRowItem);
result.set(index,notifyListRowItem);
userAdapter.notifyItemChanged(index);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.w("In ", "OnchildRemoved");
notifyListRowItem model = dataSnapshot.getValue(notifyListRowItem.class);
int index = getItemIndex(model);
result.remove(index);
userAdapter.notifyItemRemoved(index);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.w("IN", "onChildMoved");
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("IN", "onChildCancelled");
return;
}
});
}
private int getItemIndex(notifyListRowItem item){
int index = -1;
for (int i=0;i<result.size();i++){
if(result.get(i).key.equals(item.key)){
index = i;
break;
}
}
return index;
}
protected void getMac(){
GettingMac gettingMac = new GettingMac(getActivity());
user_mac = gettingMac.Mac();
}
}
You need to have an empty constructor for your Location class.
public Location () {}
You should need to add a constructor of your Location Class.
public Location() {
}

retrieving date from Firebase

I am trying to create a time line to represent all the added announcement in CardView ,
I follow every single things in this tutorial
https://www.youtube.com/watch?v=WmPGLoB28T8
but an exception throw when I was trying to retrieve the data from firebase cant now why and how to handle it :
MyHolder :
package com.volunteer.android.HolderClasses;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.volunteer.android.R;
public class AnnouncementHolder extends RecyclerView.ViewHolder {
public TextView orgtname ;
public TextView Evenname;
public CardView HomeCard ;
public TextView Start;
public TextView City;
public TextView Field;
public TextView moreinfo;
public TextView contactInfo;
public ImageView pic ;
public ImageView report ;
FirebaseAuth mAuth ;
DatabaseReference reportRef ;
public AnnouncementHolder(View view){
super(view);
mAuth=FirebaseAuth.getInstance();
reportRef= FirebaseDatabase.getInstance().getReference().child("Reports");
reportRef.keepSynced(true);
HomeCard=(CardView)view.findViewById(R.id.CardviewHome);
orgtname = (TextView) view.findViewById(R.id.textViewOragName);
Evenname = (TextView) view.findViewById(R.id.textViewEventName);
Start = (TextView) view.findViewById(R.id.TextViewDate);
City = (TextView) view.findViewById(R.id.TextViewCity);
Field = (TextView) view.findViewById(R.id.TextViewField);
moreinfo = (TextView) view.findViewById(R.id.TextViewPost);
contactInfo = (TextView) view.findViewById(R.id.contact);
pic =(ImageView)view.findViewById(R.id.ImagproSe);
report=(ImageView)view.findViewById(R.id.report_btn);
}
public void setPost_key(final String postKey){
reportRef.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
if(dataSnapshot.child(postKey).hasChild(mAuth.getCurrentUser().getUid())){
report.setImageResource(R.drawable.ic_link);
}
else {
report.setImageResource(R.mipmap.ic_report_black_24dp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
MyAdapter:
[package com.volunteer.android.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.firebase.auth.FirebaseAuth;
import com.volunteer.android.HolderClasses.AnnouncementHolder;
import com.volunteer.android.R;
import com.volunteer.android.data.Announcement;
import com.volunteer.android.data.Constants;
import java.util.ArrayList;
/**
* Created by macbookpro on 8/20/16 AD.
*/
public class AnnouncementAdapter extends RecyclerView.Adapter<AnnouncementHolder> {
Context c;
ArrayList<Announcement> Announcements = new ArrayList<>();
String Uid;
Firebase announcRef ;
Firebase reportRef ;
FirebaseAuth mAuth ;
// final String AnnKey ;
private boolean mProccesLike=false ;
public AnnouncementAdapter(Context c, ArrayList<Announcement> Announcements , String Uid){
this.c=c;
this.Announcements=Announcements;
this.Uid=Uid;
// expRef=new Firebase(Constants.USER_ECPERIENCE_PATH);
mAuth=FirebaseAuth.getInstance();
reportRef=new Firebase(Constants.FIREBASE_URL+"/Reports");
}
#Override
public void onBindViewHolder(AnnouncementHolder holder, int position) {
final Announcement announcement = Announcements.get(position);
holder.orgtname.setText((Announcements.get(position)).getOrgName());
holder.Evenname.setText((Announcements.get(position)).getEventName());
holder.contactInfo.setText((Announcements.get(position)).getContact());
holder.Field.setText((Announcements.get(position)).getField());
holder.Start.setText((Announcements.get(position)).getStartDate());
holder.moreinfo.setText((Announcements.get(position)).getMoreInfo());
holder.City.setText((Announcements.get(position)).getCity());
// holder.setPost_key(announcement.getAnnId());
holder.report.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProccesLike=true ;
reportRef.addValueEventListener(new com.firebase.client.ValueEventListener() {
#Override
public void onDataChange(com.firebase.client.DataSnapshot dataSnapshot) {
if (mProccesLike){
if (dataSnapshot.child(announcement.getAnnId()).hasChild(mAuth.getCurrentUser().getUid())){
reportRef.child(announcement.getAnnId()).child(mAuth.getCurrentUser().getUid()).removeValue();
mProccesLike=false ;
}else {
reportRef.child(announcement.getAnnId()).child(mAuth.getCurrentUser().getUid()).setValue("True");
mProccesLike=false ;
}
}}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
});
}
public void animate(RecyclerView.ViewHolder viewHolder) {
final Animation animAnticipateOvershoot = AnimationUtils.loadAnimation(c, R.anim.anticipateovershoot_interpolator);
viewHolder.itemView.setAnimation(animAnticipateOvershoot);
}
#Override
public AnnouncementHolder onCreateViewHolder (ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view_home, parent, false);
AnnouncementHolder holder =new AnnouncementHolder(v);
return holder;
}
#Override
public int getItemCount() {
return Announcements.size(); //mAssignments.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
// Insert a new item to the RecyclerView on a predefined position
public void insert(Announcement announcement, int position) {
Announcements.add(position, announcement);
notifyItemInserted(position);
}
// Remove a RecyclerView item containing a specified Data object
public void remove(Announcement announcement) {
int position = Announcements.indexOf(announcement);
Announcements.remove(position);
notifyItemRemoved(position);
}
}][1]
Saving method :
public void saveAnnouncement (View view){
org=editTextOrg.getText().toString().trim();
if (org.length()>300){
return;
}
Event=editTextEvent.getText().toString().trim();
if (Event.length()>300){
return;
}
sDate=editTextSd.getText().toString().trim();
if (sDate.length()>300){
return;}
info=editTextInfo.getText().toString().trim();
if (info.length()>300){
return;
}
contact=editTextContat.getText().toString().trim();
if (contact.length()>300){
return;
}
if (cityName==null){
return;
}
if (Feild==null){
return;
}
sDate=editTextSd.getText().toString().trim();
Announcement announcement = new Announcement(Uid,"" ,org, Event, sDate, cityName,Feild , info , contact );
//Map<String, Object> map = new HashMap<>();
// map.put("announcement",announcement);
mRef.child("Announcement").push().setValue(announcement);
The Retriving class :
package com.volunteer.android.Fragment;
/**
* Created by macbookpro on 8/23/16 AD.
*/
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.firebase.auth.FirebaseAuth;
import com.volunteer.android.R;
import com.volunteer.android.adapter.AnnouncementAdapter;
import com.volunteer.android.data.Announcement;
import com.volunteer.android.data.Constants;
import java.util.ArrayList;
/**
* Created by jnoo1 on 8/11/2016.
*/
public class Home extends Fragment {
RecyclerView rv ;
ArrayList<Announcement> announcements = new ArrayList<>();
AnnouncementAdapter adapter ;
Firebase myRef ;
FloatingActionButton AddAnouncement ;
FirebaseAuth mAuth ;
String Uid ;
public Home(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view =inflater.inflate(R.layout.fragment_etailse,container,false);
Firebase.setAndroidContext(getActivity());
myRef = new Firebase(Constants.FIREBASE_URL);
rv =(RecyclerView)view.findViewById(R.id.recyclerViewHome);
rv.setLayoutManager(new LinearLayoutManager(getActivity()));
AddAnouncement=(FloatingActionButton) view.findViewById(R.id.fab1);
mAuth=FirebaseAuth.getInstance();
Uid=mAuth.getCurrentUser().getUid();
adapter=new AnnouncementAdapter(getActivity(),announcements,Uid);
rv.setAdapter(adapter);
RefreshData();
return view ;
}
public void RefreshData (){
myRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
getUpdates(dataSnapshot);}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
getUpdates(dataSnapshot);}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
getUpdates(dataSnapshot);}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
#Override
public void onCancelled(FirebaseError firebaseError) {}
}); }
private void getUpdates (DataSnapshot dataSnapshot ){
announcements.clear();
for (DataSnapshot Ds : dataSnapshot.getChildren())
{
Announcement announcement=new Announcement();
announcement.setOrgName( Ds.getValue(Announcement.class).getOrgName());
announcement.setEventName(Ds.getValue(Announcement.class).getEventName());
announcement.setCity(Ds.getValue(Announcement.class).getCity());
announcement.setField(Ds.getValue(Announcement.class).getField());
announcement.setStartDate(Ds.getValue(Announcement.class).getStartDate());
announcement.setMoreInfo(Ds.getValue(Announcement.class).getMoreInfo());
announcement.setContact(Ds.getValue(Announcement.class).getContact());
// announcement.setAnnId((String) Ds.getKey());
//exp.setCity((String) dataSnapshot.child("city").getValue());
announcements.add(announcement);
}
if (announcements.size()>0){
adapter=new AnnouncementAdapter(getActivity(),announcements,Uid);
rv.setAdapter(adapter); }
else {
Toast.makeText(getActivity() ," No thing to show ", Toast.LENGTH_SHORT).show(); } }
}
The error crash my app evrytime :
09-15 17:11:35.622 5862-5884/com.volunteer.android I/DynamiteModule: Considering local module com.google.android.gms.tagmanager:3 and remote module com.google.android.gms.tagmanager:3
09-15 17:11:35.622 5862-5884/com.volunteer.android I/DynamiteModule: Selected local version of com.google.android.gms.tagmanager
09-15 17:11:35.648 5862-5884/com.volunteer.android W/GoogleTagManager: Tag Manager's event handler WILL NOT be installed (no container loaded)
09-15 17:11:35.648 5862-5884/com.volunteer.android I/GoogleTagManager: Tag Manager initilization took 23ms
09-15 17:11:35.819 5862-5862/com.volunteer.android D/FirebaseCrashApiImpl: throwable com.firebase.client.FirebaseException: Failed to bounce to type
09-15 17:11:35.849 5862-5862/com.volunteer.android E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.volunteer.android, PID: 5862
com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
at com.volunteer.android.Fragment.Home.getUpdates(Home.java:107)
at com.volunteer.android.Fragment.Home.access$000(Home.java:32)
at com.volunteer.android.Fragment.Home$1.onChildAdded(Home.java:85)
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "UserInformation" (class com.volunteer.android.data.Announcement), not marked as ignorable (11 known properties: , "contact", "moreInfo", "eventName", "city", "orgName", "startDate", "uid", "field", "annId", "picture", "key"])
at [Source: java.io.StringReader#1a04a2ef; line: 1, column: 21] (through reference chain: com.volunteer.android.data.Announcement["UserInformation"])
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1160)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:181)
at com.volunteer.android.Fragment.Home.getUpdates(Home.java:107) 
at com.volunteer.android.Fragment.Home.access$000(Home.java:32) 
at com.volunteer.android.Fragment.Home$1.onChildAdded(Home.java:85) 
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48) 
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45) 
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
09-15 17:11:36.234 5993-5993/com.volunteer.android:background_crash W/DynamiteModule: Local module descriptor class for com.google.android.gms.crash not found.
package com.volunteer.android.data;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.firebase.database.Exclude;
/**
* Created by macbookpro on 8/10/16 AD.
*/
public class Announcement {
#JsonIgnore
private String Key ;
private String OrgName;
private String EventName;
private String StartDate;
private String City;
private String Field;
private String MoreInfo;
private String Contact;
private String Picture;
private String Uid;
private String AnnId ;
public Announcement (){
// defualt ;
}
public Announcement (String Uid, String AnnId ,String OrgName,String EventName,String StartDate,String City,String Field, String MoreInfo, String Contact){
this.Uid=Uid;
this.AnnId=AnnId;
this.OrgName=OrgName;
this.EventName=EventName;
this.StartDate=StartDate;
this.City=City;
this.Field=Field;
this.MoreInfo=MoreInfo;
this.Contact=Contact;
}
public void setAnnId (String AnnId){this.AnnId=AnnId;}
public String getAnnId (){return AnnId;}
public void setKey(String Key){
Key=Key;
}
#Exclude
public String getKey(){
return Key;
}
public void setUid (String Uid){this.Uid=Uid;}
public String getUid (){return Uid ; }
public void setOrgName(String orgName){
OrgName=orgName;
}
public String getOrgName(){
return OrgName;
}
public void setEventName(String EName){
EventName=EName;
}
public String getEventName(){
return EventName;
}
public void setStartDate(String Date){
StartDate= Date;
}
public String getStartDate(){
return StartDate;
}
public void setCity(String c){
City=c;
}
public String getCity(){
return City;
}
public void setField(String f){
Field=f;
}
public String getField(){
return Field;
}
public void setMoreInfo(String m){
MoreInfo=m;
}
public String getMoreInfo(){
return MoreInfo;
}
public void setContact(String Contact){
this.Contact=Contact;
}
public String getContact(){
return Contact;
}
public void setPicture(String p){
Picture=p;
}
public String getPicture(){
return Picture;
}
}

cannot resolve constructor for FirebaseListAdapter (Android)

I'm trying to follow along with the following tutorial:
Retrieving data in realtime with Firebase Events - Firecasts #2
Around the 14:00 minute mark, you will see the following code introduced:
FirebaseListAdapter<String> adapter = new FirebaseListAdapter<String>(this,
String.class, android.R.layout.simple_list_item_1, messagesRef) {
protected void populateView(View v, String model, int position) {
TextView textView = (TextView) findViewById(android.R.id.text1);
textView.setText(model);
}
};
However my Android Studio underlines the constructor parameters in red and when I hover my mouse over the underlined area, a message pops up saying "cannot resolve constructor '[elaborate abstract description of my constructor w/ params]'. I wish I could cut and paste what it says exactly, but I can't find any way of doing that.
Anyhow... In my infinite knowledge, I inspected the underlying (imported) class, FirebaseListAdapter.java (in case there had been some kind of changes to the constructor requirements since the video was made), and I can see no reason why my constructor (which isn't really "my" constructor -- it's the one from the video) doesn't work.
Thanks for any help!
PS - I know someone is going to ask for more code so here is the entire MainActivity:
package com.testing123.firecast2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.firebase.ui.database.FirebaseListAdapter;
import java.util.ArrayList;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
ArrayAdapter<String> adapter;
static final String TAG = "FireBase2";
// Firebase
Firebase mRootRef;
Firebase messagesRef;
// ArrayList<String> mMessages = new ArrayList<>();
// UI
TextView mTextView;
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRootRef = new Firebase ("https://firecast002.firebaseio.com/");
mTextView = (TextView) findViewById(R.id.textView);
mListView = (ListView) findViewById(R.id.listView);
}
#Override
protected void onStart() {
super.onStart();
messagesRef = mRootRef.child("messages");
// adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mMessages);
FirebaseListAdapter<String> adapter = new FirebaseListAdapter<String>(this,
String.class, android.R.layout.simple_list_item_1, messagesRef) {
protected void populateView(View v, String model, int position) {
TextView textView = (TextView) findViewById(android.R.id.text1);
textView.setText(model);
}
};
mListView.setAdapter(adapter);
/* messagesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// String message = dataSnapshot.getValue(String.class);
// mTextView.setText(message);
// that was how its done for single key value pair... but now we're doing multiple children under "message"
Map<String,String> map = dataSnapshot.getValue(Map.class);
String message1 = map.get("message1");
String message2 = map.get("message2");
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
}); */
// that was how its done for valuevent listener... now we treat the children of "message" key as list items
// and use a childeventlistener instead
/* messagesRef.addChildEventListener(new ChildEventListener() {
#Override
// gets fired for every INITIAL child member.
// only gets sent a string, not a downstream dataset
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
String message = dataSnapshot.getValue(String.class);
Log.i(TAG, "child added: " + message + " ... and by the way, String 's' is" + s);
mMessages.add(message);
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String message = dataSnapshot.getValue(String.class);
Log.i(TAG, "child changed: " + message + " ... and by the way, String 's' is" + s);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String message = dataSnapshot.getValue(String.class);
Log.i(TAG, "child removed: " + message);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
*/
// that was the hard way, now we use FirebaseUI
}
}
Update your project to add the latest version of firebase UI
'com.firebaseui:firebase-ui:0.4.3'
I had the same error. After many tries I think I found a solution.
First, add this library to your dependencies:
implementation 'com.firebaseui:firebase-ui:0.6.2'
Next, copy and paste this import to your activity import:
import com.firebase.ui.database.FirebaseListAdapter;

Categories

Resources