locked
How to retrieve data from firebase database into xamarin android app RRS feed

  • Question

  • User381688 posted

    I am trying to retrieve data from firebase. But, i couldn't find a method to retrieve data from firebase database. Now i am out of ideas please help me.

    Monday, January 21, 2019 3:46 PM

All replies

  • User371688 posted

    I have developed a chat app by FireBase ,and it works well. The Object I used to comunicated with FireBase Server is as follows:

      class FriendlyMessage : Java.Lang.Object, IParcelable
       {
        public String text;
        public String name;
        public String photoUrl;
        public String UId;
         public FriendlyMessage(String text, String name, String photoUrl)
        {
            this.text = text;
            this.name = name;
            this.photoUrl = photoUrl;
            this.UId = Guid.NewGuid().ToString();
        }
    
         public static HashMap MsgModelToMap(FriendlyMessage msg)
        {
            HashMap map = new HashMap();
    
            map.Put("text", msg.text);
            map.Put("name", msg.name);
            map.Put("photoUrl", msg.photoUrl);
            map.Put("UId", msg.UId);
    
            return map;
        }
    
        public static FriendlyMessage MapToMsgModel(DataSnapshot snapShot)
        {
            FriendlyMessage msg = new FriendlyMessage();
    
            if (snapShot.GetValue(true) == null)
            {
                return null;
            }
    
            msg.UId = snapShot.Key;
            msg.text = snapShot.Child("text")?.GetValue(true)?.ToString();
            msg.name = snapShot.Child("name")?.GetValue(true)?.ToString();
            msg.photoUrl = snapShot.Child("photoUrl")?.GetValue(true)?.ToString();
    
            return msg;
    
        }
        //............
      }
    

    The first three fields are stored in Database as follows:

    The main code to communicate with FireBase database is as follows : 1. send message to FireBase database

      public class MainActivity : AppCompatActivity,IOnClickListener,IOnSuccessListener
    {
        public static readonly String ANONYMOUS = "anonymous";
        public static readonly int DEFAULT_MSG_LENGTH_LIMIT = 1000;
        public static readonly int RB_SIGNED_IN = 1;
        private static readonly int RC_PHOTO_PICKER = 2;
    
        private ListView mMessageListView;
        private static MessageAdapter mMessageAdapter;
        private ProgressBar mProgressBar;
        private ImageButton mPhotoPickerButton;
        private EditText mMessageEditText;
        private Button mSendButton;
    
        private String mUsername;
    
        private FirebaseDatabase mFirebaseDatabase;
        private DatabaseReference mMsgDatabaseReference;
        private IChildEventListener mChildEventListener;
    
        //********************************************************************
        private FirebaseStorage mFirebaseStorage;
        private StorageReference mChatPhotosStorageRef;
        //********************************************************************
        private FirebaseAuth auth;
        //private FirebaseAuth.IAuthStateListener authStateListener;
    
        private static string mUserName = "";
    
       static List<FriendlyMessage> msgList = new List<FriendlyMessage>();
    
        //private TextView msgText;
    
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
    
            SetContentView(Resource.Layout.activity_main);
            //my chat app code
            IsPlayServicesAvailable();
         //...............
            mPhotoPickerButton = FindViewById<ImageButton>(Resource.Id.photoPickerButton);
            mMessageEditText = FindViewById<EditText>(Resource.Id.messageEditText);
            mSendButton = FindViewById<Button>(Resource.Id.sendButton);
    
            mPhotoPickerButton.SetOnClickListener(this);
    
            mUsername = ANONYMOUS;
            mFirebaseDatabase = FirebaseDatabase.Instance;
            mFirebaseStorage = FirebaseStorage.Instance;
            mMsgDatabaseReference = mFirebaseDatabase.Reference.Child("messages");
            mChatPhotosStorageRef = mFirebaseStorage.Reference.Child("chat_photos");
    
            //mFirebaseAuth = FirebaseAuth.Instance;
            auth = FirebaseAuth.GetInstance(LoginActivity.app);
            //authStateListener = new AuthStateListener(this);
            if (auth.CurrentUser != null)
            {
                mUserName = auth.CurrentUser.Email;
            }
    
    
            // Initialize progress bar
            mProgressBar.Visibility = Android.Views.ViewStates.Invisible;
            mSendButton.Click += delegate {
                // TODO: Send messages on click
                FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.Text, mUsername, null);
                //Java.Lang.Object obj = Java.Lang.Class.FromType(typeof(FriendlyMessage));
                mMsgDatabaseReference.Push().SetValue(FriendlyMessage.MsgModelToMap(friendlyMessage));
                // Clear input box
                mMessageEditText.Text="";
    
            };
            attachDataBaseReadListener();
    
    //......................
    
        }     
    

    2. method attachDataBaseReadListener :

       private void attachDataBaseReadListener() {
            if (mChildEventListener == null) { 
            mChildEventListener = new ChildMsgEventListener();
            mMsgDatabaseReference.AddChildEventListener(mChildEventListener);
            }
        }
    
     private class ChildMsgEventListener : Java.Lang.Object, IChildEventListener
        {
            public void OnCancelled(DatabaseError error)
            {
                throw new NotImplementedException();
            }
    
       // when added the item , you can retrieve the data from the database
            public void OnChildAdded(DataSnapshot snapshot, string previousChildName)
            {
                var obj = snapshot.Children;
                foreach (DataSnapshot s in obj.ToEnumerable())
                {
                    var model = FriendlyMessage.MapToMsgModel(snapshot);
    
                    if (model != null && !IsExisting(model)) {
                        Log.Debug(TAG,"current model = " + model.ToString());
                        msgList.Add(model);
                    }
                }
               mMessageAdapter.NotifyDataSetChanged();
            }
            public void OnChildChanged(DataSnapshot snapshot, string previousChildName)
            {
                throw new NotImplementedException();
            }
            public void OnChildMoved(DataSnapshot snapshot, string previousChildName)
            {
                throw new NotImplementedException();
            }
            public void OnChildRemoved(DataSnapshot snapshot)
            {
                throw new NotImplementedException();
            }
        }
    
    Tuesday, January 22, 2019 2:47 PM
  • User371688 posted

    Have you got your solution at last?

    Tuesday, February 12, 2019 7:46 AM
  • User390490 posted

    Can you provide the full code

    Tuesday, December 3, 2019 3:28 AM
  • User390490 posted

    Including the class name

    Tuesday, December 3, 2019 3:29 AM
  • User33165 posted

    Thanks, this really helped me in using firebase realtime database in contrast to other information found on the internet. :)

    Thursday, April 9, 2020 10:31 AM