Real time database firebase - firebase-realtime-database

I have some problems with Real time Database of Firebase for my Android App, because I can’t see any data. I don’t know why, I have also changed the rules yet.
I have three classes in my Android project: LogIn, SignUp (for registration) and Profile. When I write "name", "username","lastname", "email" and "password" in the SignUp class, then I can see the "name" "lastname" and "username" in the Profile, but not in the Real time DataBase.
Here there is part of the code:
SignUp:
declaration of variables:
private lateinit var dbReference: DatabaseReference
private lateinit var firebaseDatabase: FirebaseDatabase
and then.....
rebaseDatabase = FirebaseDatabase.getInstance()
dbReference = firebaseDatabase.getReference("users")
dbReference.setValue("First users")
val currentDb = dbReference.child((currentUser?.uid!!))
currentDb.child("name").setValue(name)
currentDb.child("lastname").setValue(lastName)
currentDb.child("user").setValue(user)
currentDb.child("email").setValue(email)
currentDb.child("pass").setValue(pass)
Profile class:
database = FirebaseDatabase.getInstance()
databaseReference = database?.reference!!.child("users")
override fun onDataChange(snapshot: DataSnapshot) {
val usernameText = findViewById<TextView>(R.id.usernameText)
val nameText = findViewById<TextView>(R.id.nameText)
val lastnameText = findViewById<TextView>(R.id.lastnameText)
usernameText.text = snapshot.child("user").value?.toString()
nameText.text= snapshot.child("name").value?.toString()
lastnameText.text= snapshot.child("lastname").value?.toString()
}
[enter image description here][1]
[1]: https://i.stack.imgur.com/liW2z.jpg

Can you try this in ur Signup:
private lateinit var dbReference: DatabaseReference
dbReference = Firebase.database.reference;
dbReference.child("users").setValue("First users")
instead of
private lateinit var dbReference: DatabaseReference
private lateinit var firebaseDatabase: FirebaseDatabase.getInstance()
dbReference = firebaseDatabase.getReference("users")
dbReference.setValue("First users")
you may have jumbled up java and kotlin code. As shown in the page https://firebase.google.com/docs/database/android/read-and-write
UPDATE :
I would like to add something. I didnt see this at first but it seems important and is mentioned in page https://firebase.google.com/docs/database/android/read-and-write
Can you try this
dbReference = Firebase.database("https://soundbliss-8ba73-default-rtdb.europe-west1.firebasedatabase.app").reference;
instead of
dbReference = Firebase.database.reference;
If this doesn't work, find out the database url of your firebase project and then pass it as an argument to the database function like this
dbReference = Firebase.database("database url of ur app").reference;

Related

Access modification Apple Combine

I'm trying to think in terms of API Design because ultimately I want to ship code to myself or others.
Let's make some assumptions in order to get a succinct scenario. We will assume I have some Code that authenticates with my server and returns a user object. Defined simply like this:
public struct User: Codable {
public let id: UUID
public let email: String
public let name: String
}
I'm writing this code as an SDK I would ship to myself or a third party where all the guts of AUTH are handled. Using Apples new Combine framework I might expose a publisher for the consumer of my SDK like this.
public enum CurrentUserError: Error {
case loggedOut
case sessionExpired
}
public struct MyAuthFrameworkPublishers {
static let currentUser: CurrentValueSubject<User?, CurrentUserError> = CurrentValueSubject<User?, CurrentUserError>(nil)
}
Now, my private auth could accomplish it's task and retrieve a user then publish that to anything outside the SDK that it listening like so:
class AuthController {
func authenticate() {
///Get authenticated user.
let user = User.init(id: UUID(), email: "some#some.com", name: "some")
MyAuthFrameworkPublishers.currentUser.send(user)
}
}
let authController = AuthController.init()
authController.authenticate()
Is there a way to keep or stop the user of this SDK from sending it's own User object to the publisher? Like a private or access controller .send() function in combine?
Do you really want to use CurrentUserError as your Failure type? Sending a failure ends any subscriptions to the subject and fails new ones immediately. If the session expires, don't you want to let the user log in again? That would require publishing another User? output, which you cannot do if you have published a failure.
Instead, use Result<User?, CurrentUserError> as your Output type, and Never as your Failure type.
Now, on to your question. In general, the way to prevent the user from calling send is to vend an AnyPublisher instead of a Subject:
public class AuthController {
public let currentUser: AnyPublisher<Result<User?, AuthenticationError>, Never>
public func authenticate() {
let user: User = ...
subject.send(user)
}
public init() {
currentUser = subject.eraseToAnyPublisher()
}
private let subject = CurrentValueSubject<Result<User?, AuthenticationError>, Never>(nil)
}

Kotlin No setter/field for Value found on class Object warning for Firebase

I'm trying to fetch all messages data inside my ChatMessage data class from my Firebase Database. In the logs, I can see that data is indeed fetched inside my Snapshot, but it isn't getting assigned to my variables in the data class. I'm new to Kotlin & Firebase, so I don't really understand why is it happening?
After I did some logs searching I found out that I have been receiving this warning:
W/ClassMapper: No setter/field for -Llk34LtqGPJ3bwPrYRi found on class com.idiotboxes.socialowl.models.ChatMessage
Did some searching for this error here & found it is a very common problem indeed. But my issue, none of the solutions have a data class format like mine.
I understand that the warning is saying I need to setup getters & setters in my data class, but I'm fairly new to Kotlin & I don't know how to implement getter-setters in my data class.
Here's how my data class ChatMessage looks like:
package com.idiotboxes.socialowl.models
data class ChatMessage(val messageID: String, val fromID: String, val toID:
String,val message: String, val timeStamp: Long){
//No argument constructor
constructor(): this("","","","",-1)
}
Here is how my Firebase Database node looks like:
Database Structure
EDIT: Here's extra code to help you understand where the problem could be
My Callback interface
interface FirebaseCallback {
fun onCallback(latestMessage: ChatMessage)
}
My function which reads the Data from Firebase
private fun readFirebaseData(firebaseCallback: FirebaseCallback){
//Signed In user's ID
val fromID = FirebaseAuth.getInstance().uid
Log.w(TAG, "from ID is: $fromID (Currently Signed-In user)")
//Get Database Reference
val msgRef = FirebaseDatabase.getInstance().getReference("/Latest-messages/$fromID"/* Reference to current user's database entry */)
//Set a Listener for new messages
msgRef.addChildEventListener(object: ChildEventListener {
//adds new row when someone messages you for the first time, i.e. New Child is Added
override fun onChildAdded(p0: DataSnapshot, p1: String?) {
Log.w(TAG, "Snapshot captured from Firebase Database is: $p0")
//Convert snapshot to messages
//val latestMessage = p0.getValue(ChatMessage::class.java) ?: return
val callbackData: ChatMessage = p0.getValue(ChatMessage::class.java) ?: return
//TODO Implement Callback
firebaseCallback.onCallback(callbackData)
}
//Updates existing rows latest messages when user receives new message i.e. Latest Message child is Changed.
override fun onChildChanged(p0: DataSnapshot, p1: String?) {
val latestMessage: ChatMessage = p0.getValue(ChatMessage::class.java) ?: return//If Null then return
//Update the Existing row with new message
latestMessagesHashMap[p0.key!!] = latestMessage
updateRecyclerView()
}
--Some redundant methods of ChildEventListener--
})
latest_messages_recycler_view.adapter = adapter
//Recycler View Bottom Line Border
latest_messages_recycler_view.addItemDecoration(DividerItemDecoration(activity, DividerItemDecoration.VERTICAL))
}
Function where I attempt to retrieve data from my callback
private fun showLatestMessages(){
readFirebaseData(object : FirebaseCallback{
override fun onCallback(latestMessage: ChatMessage) {
//TODO latestMessage is not null. But blank values are being filled in the Chat Message model class
Log.w(TAG, "NotNull latestMessage values are fromID: ${latestMessage.fromID} toID: ${latestMessage.toID} Typed Message: ${latestMessage.message} TimeStamp: ${latestMessage.timeStamp}")
//Add the new message row
adapter.add(LatestMessagesItems(latestMessage, context ?: return))
}
})
//Set OnClick Listener on Recycler View Items
adapter.setOnItemClickListener { item, view ->
//Grab the User details from the item that is clicked.
val userItem = item as LatestMessagesItems
//Start Chat Activity with the clicked User
val startChat = Intent(activity, ChatActivity::class.java)
startChat.putExtra(USER_KEY, userItem.recipientUser)
startActivity(startChat)
}
}
private fun updateRecyclerView(){
//Clear existing rows
adapter.clear()
//Fetch all Latest Messages from HashMap
latestMessagesHashMap.values.forEach {
adapter.add(LatestMessagesItems(it, context?: return))
}
}
My messages item for my recyclerview
class LatestMessagesItems(val latestMessage: ChatMessage, val ctx: Context): Item<ViewHolder>(){
lateinit var recipientUser: User
override fun getLayout(): Int {
return R.layout.latest_message_row
}
override fun bind(viewHolder: ViewHolder, position: Int) {
Log.w(TAG, "Fetched latest Message is: $latestMessage")
//Null Check
val recipientID: String? = if (latestMessage.fromID == FirebaseAuth.getInstance().uid) {
latestMessage.toID
} else {
latestMessage.fromID
}
//Fetch the recipient user details
val fetchRef = FirebaseDatabase.getInstance().getReference("/users/$recipientID")
fetchRef.addListenerForSingleValueEvent(object: ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
Log.w(TAG, "Fetched Recipient ID is: $recipientID")
//Fetch user details in User model class
recipientUser = p0.getValue(User::class.java) ?: return
Log.w(TAG, "Fetched Recipient User Name is: ${recipientUser.username}")
//Fill the User Details
viewHolder.itemView.recipient_username.text = recipientUser.username //Username
Glide.with(ctx).load(recipientUser.profileImage).into(viewHolder.itemView.recipient_profile_image) //Profile Pic
}
override fun onCancelled(p0: DatabaseError) {
}
})
//Latest Message Received
viewHolder.itemView.latest_received_message.text = latestMessage.message
}
}
And Finally I updated my Model Class according to some of the suggestions posted here.
ChatMessage.kt
package com.idiotboxes.socialowl.models
data class ChatMessage(var messageID: String? = null, var fromID: String? = null , var toID: String? = null ,var message: String? = null , var timeStamp: Long? = null){
//No argument constructor
constructor(): this("","","","",-1)
}
Yet, the problem still persists.
I can't say for sure it's the case but I think that you should write to variables (var), not values (val).
This is because Kotlin automatically generates getters/setters for var, which is considered mutable, and doesn't for val which is considered immutable.
The same happens for private vars as Kotlin doesn't provide getters/setters for them outside their local scope (e.g. for Firebase to access them).

Using custom model class with Backendless in Swift

I'm trying to retrieve data from an online data storage using the func that I found online on the official Backendless docs! but when I try to use persona like a Lista(my own class) Object, I get the error: Could not cast value of type '__NSDictionaryM' (0x10c1ccfc0) to 'InLIsta_.Lista' (0x108439790).
I search over this site but the answer aren't specific for the Backendless case, so I hope that anyone can help me
this is my code (obviously I've declared all the var and let necessary to the code to run):
class Lista : NSObject {
var nome: String?
var pr: String?
var pagamento = 0
var entrato: Bool = false
var commenti: String?
var objectId: String?
var created: NSDate?
var updated: NSDate?
}
func findQ() {
Types.tryblock({ () -> Void in
let startTime = NSDate()
let found = self.backendless.persistenceService.of(Lista.ofClass()).find(self.query)
let currentPage = found.getCurrentPage()
print("Loaded \(currentPage.count) name objects")
print("Total name in the Backendless storage - \(found.totalObjects)")
for person in currentPage {
let persona = person as! Lista // here i get error
print("Restaurant <\(Lista.ofClass())> name = \(persona.nome)")
self.nomi.append(persona.nome!)
}
print("Total time (ms) - \(1000*NSDate().timeIntervalSinceDate(startTime))")
},
catchblock: { (exception) -> Void in
print("Server reported an error: \(exception as! Fault)")
}
)
}
The backendless persistence service has a method -(void)mapTableToClass:(NSString *)tableName type:(Class)type; that you need to call for each of your custom classes so they'll be used during the deserialisation.
self.backendless.persistenceService.mapTableToClass("Lista", type: Lista.self)
This needs to be done before any calls are made to use the persistence service.
Note that the classes, if not defined in obj-c, must be exported to obj-c. Note that this also means you can't have any optionals.
Ideally you should use the platform code generation to create your model class definitions to ensure all of the attributes are created with the appropriate types. A failure to map to your custom class could be caused by type mismatches or name mismatches. Optionals will always fail in the current SDK implementation.

Working with Access Control in swift?

I want to get device ID in at all classes level in swift which will be included as parameter every time async call made.And I really don't get clearly about Apple Access Control.So,I really need help
So,How to make saving device id at start point and them accessible to all classes for async request?
In app,didFinishLaunchingWithOptions,I will add the following code
let say keychain is the library where i store value
if keychain.get("deviceID") == nil{
keychain.set(UIDevice.currentDevice().identifierForVendor!.UUIDString,forKey : ”deviceID”)
//some private var deviceID = keychain.get(“deviceID”)
}
else{
some private var deviceID = keychain.get(“deviceID”)
}
And I want to access that private var at everywhere in the UIViewController class.
class ViewController : UIViewController {
let deviceID = //some private var with getter?
}
Is there any idea that i can do in swift?using Apple Access Control?
And that problem is connected to that question : Getting Device ID is not unique
define your deviceID as static and you will be able to access it everywhere
after your code to initiate the keychain, set it as a static at some class
class DeviceArg {
static var deviceId = keychain.get(“deviceID”)
}
// some other place in the code
let check = DeviceArg.deviceId //get deviceId
Check My Code :-
var mytoken1: String = deviceToken.description.stringByReplacingOccurrencesOfString("<", withString: "")
var mytoken2: String = mytoken1.stringByReplacingOccurrencesOfString(">", withString: "")
mytoken2 = mytoken2.stringByReplacingOccurrencesOfString(" ", withString: "")
NSUserDefaults.standardUserDefaults().setValue(mytoken2, forKey: "DEVICE_TOKEN")
NSUserDefaults.standardUserDefaults().synchronize()

"foreign key" as primary key in realm

I'm getting started with realm and trying to figure out the best way to write my model layer, so after overthinking about it I decide to ask here to get some opinions. Here we go:
I'm writing a realm version of these tables:
Account
id - String (PK)
Name - String
Type - Int
Checking Account
id - String (FK PK)
In this case a Checking Account is an Account, but realm still not support inheritance (I think using Account as a superclass would be the better way to figure these tables out in the model layer)
This is what I actually did with realm:
Account class:
import Foundation
import RealmSwift
class Account: Object {
dynamic var id = NSUUID().UUIDString
dynamic var name = ""
dynamic var type = 3
override static func primaryKey() -> String {
return "id"
}
}
Checking Account class:
import Foundation
import RealmSwift
class CheckingAccount: Object {
dynamic lazy var id: String = {
return self.account.id
}()
dynamic var account = Account()
convenience init(name: String, type: AccountType) {
self.init()
self.account.name = name
self.account.type = type.rawValue
}
override static func primaryKey() -> String? {
return "id"
}
}
What about it? It's a "Don't do" way to figure out my SQL tables with realm?
Thank you!

Resources