Pass data from recyclerview to firebase - firebase

I try to save data from recyclerview to firebase, but there are an error, because the data are null, and i don't know why
Recyclerview code
Class
Pass data

Here you are actually saving it firebase and then assigning the value.When you create object value for student there will not value.
Also additional note, as per your code when give adapter.names.String() will save all the names in a single field in firebase database.
private fun SaveStudents (student: Students) {
var database = Firebase.database.reference
student.idStudent = UUID.randomUUID().tostring
student.name = adapter.names.toString()
student.noControl = adapter.details.toString()
//Student data populated
//Then save it to firebase.
database.child("students").child(student.idStudent).setValue(student)
}

Related

How to Convert Dart Snapshot object data to String Variables from Flutter Firestore?

I am Performing CRUD operations with Flutter Firestore. Here i want to Read data from Firestore i have a Peace of code here.
var noteInfo = snapshot.data!.docs[index].data()!;
String docID = snapshot.data!.docs[index].id;
print(noteInfo.toString());
here noteInfo contains Following data
{description: My Name is Qasim, title: Qasim}
Now i have two String Variables Name where i want to store title attribute of noteInfo and des where i want to store description attribute of object noteInfo. Data from Firestore is fetched. I just want to store these two attributes in seprate string variables.
As far as I can see in your code, noteInfo is a Map. So you can get the values for those two variables with:
var title = noteInfo["title"];
var description = noteInfo["description"]
To get the data as a map, use:
var noteInfo = snapshot.data!.docs[index].data()! as Map;
Also see: Convert Firestore DocumentSnapshot to Map in Flutter

Flutter Firebase firestore append data with unique ID

I'm working on the Flutter app where users can save multiple addresses. Previously I used a real-time database and it was easier for me to push data in any child with a unique Id but for some reason, I changed to Firestore and the same thing want to achieve with firestore. So, I generated UUID to create unique ID to append to user_address
This is how I want
and user_address looks like this
And this is how it's getting saved in firestore
So my question Is how I append data with unique id do I have to create a collection inside users field or the above is possible?
Below is my code I tried to set and update even user FieldValue.arrayUnion(userServiceAddress) but not getting the desired result
var uuid = Uuid();
var fireStoreUserRef =
await FirebaseFirestore.instance.collection('users').doc(id);
Map locationMap = {
'latitude': myPosition.latitude,
'longitude': myPosition.longitude,
};
var userServiceAddress = <String, dynamic>{
uuid.v4(): {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
}
};
await fireStoreUserRef.update({'user_address': userServiceAddress});
If I use set and update then whole data is replaced with new value it's not appending, so creating a collection is the only solution here and If I create a collection then is there any issue I'll face?
You won't have any issues per se by storing addresses in a separate collection with a one-to-many relationship, but depending on your usage, you may see much higher read/write requests with this approach. This can make exceeding your budget far more likely.
Fortunately, Firestore allows updating fields in nested objects via dot notation. Try this:
var userServiceAddress = {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
};
await fireStoreUserRef.update({'user_address.${uuid.v4()}': userServiceAddress});

Flutter/Dart/Firebase - Updated nested map values

I am trying to record which on my users has purchased which ticket in my app. I am using firebase to store my data about my users and giveaways. When a purchase is complete, I am trying to update the relevant giveaway and assign each ticket to a user using their id.
Firstly, I am not sure if my data schema is the most appropriate for what I'm trying to achieve so open to suggestions for editing as I'm still quite new to the flutter world.
Second, here is how my data is currently structured:
Here is how I have structured my code. Here is my SingleBasketItem model:
class SingleBasketItem {
final String id;
final String uid;
final OurGiveAways giveaway;
final int ticketNumber;
SingleBasketItem(this.id, this.uid, this.giveaway, this.ticketNumber);
}
Here is my Shopping Basket model, I have added an Elevated Button to my shopping basket page which, when tapped, will execute the placeOrder() function:
class ShoppingBasket extends ChangeNotifier {
Map<String, SingleBasketItem> _items = {};
Map<String, SingleBasketItem> get items {
return {..._items};
}
void addItem(String id, String uid, OurGiveAways giveaway, int ticketNumber) {
_items.putIfAbsent(
id,
() => SingleBasketItem(id, uid, giveaway, ticketNumber),
);
notifyListeners();
}
void placeOrder(BuildContext context, OurUser user) {
for (var i = 0; i < _items.length; i++) {
FirebaseFirestore.instance
.collection('giveaways')
.doc(_items.values.toList()[i].giveaway.giveawayId)
.update(
{
'individual_ticket_sales'[_items.values.toList()[i].ticketNumber]:
user.uid,
},
);
}
}
}
Below is an image of the results:
By analysing the results it looks like my code is creating a new field with a title of the 1st index character of individual_ticket_sales ("n" because ive bought ticket 1), how can I set the nested "1" (or whatever ticket I choose) to my user id rather than creating a new field? Thanks.
I would recommend to refactor your database structure because the first problem you will hit with that one is that firestore for now does not support updating a specific index for an array field value. You can get more info about that here.
You could get the whole value individual_ticket_sales update it and save it again as whole but it would be just a matter of time when you would hit the problem that multiple users want to update the same value on almost the same time and one of the changes get's lost. Even the usage of transaction would not be 100% safe because of the size of the object and potential multiple changes.
Is it possible for you to store each ticketId as a firestore document in a firestore collection like this:
FirebaseFirestore.instance
.collection('giveaways')
.doc(_items.values.toList()[i].giveaway.giveawayId)
.collection('individual_ticket_sales')
.doc(i)
.update(user.uid);

How to pre-populated database from assets using floor with flutter?

I created a database that contains a table that already has data and I initialized floorDatabase in my flutter app, and I found the table but without data, it was empty. I have been trying to solve this for 2 days but I don't know what is the problem, in android it works, any help!
Here is my code: here to initialize and get the data
Future<List<CinemaTable>> getAllCinema() async{
final database = await $FloorMovieDatabase.databaseBuilder('Databases/NotifyDB.db').build();
var list = await database.movieDao.getAllCinema();
return list;
}
Database Class:
#Database(version: 1, entities: [CinemaTable, FavouriteTable])
abstract class MovieDatabase extends FloorDatabase {
MovieDao get movieDao;
}
Here is a screenshot of the table with the data in SQLLite browser
Here is the table in android studio
.......

How to filter field value and send data into the firestore collection?

In the firestore collection named 'doctor' there are different fields including the field 'role'. I want to add the doctors into firestore with a role named doctor. How can I do this? Following is the code that successfully adds data into the database. If you can, tell me the way to add data with a specific field name. Thanks in advance.
service.ts
create_Newdoctor(Record){
return this.firestore.collection('doctors').add(Record);
}
component.ts
CreateRecord(docForm: NgForm){
let Record = {};
Record['fullName']=this.fullName;
Record['email']=this.email;
this.DoctorService.create_Newdoctor(Record).then(res=> {
this.fullName="";
this.email="";
console.log(res);
this.message = "Added";
}).catch(error=>{
console.log(error);
});
}
Notice that Record is a javascript object, and how you create a document in Cloud firestore, is by passing an object with all the filled attributes into the add method like what you did in service.ts, and how you pass in an attribute is via Record[ATTRIBUTE_NAME] = ATTRIBUTE_VALUE
Hence I believe what you need to just to add in the line Record[‘role’] = “doctors” into component.ts

Resources