android – Firebase RecyclerView com Section

Bom, eu estou a dias tentando criar um recyclerView com seções usando o firebase mas nada funciona… Eu estou tentando fazer algo como, por exemplo, em Janeiro fica alguns itens, em Fevereiro outros e por ai vai. Eu consegui usar o firebase pra fazer o recyclerView e tudo mais, mas não faço ideia de como separar os dados daquela forma que expliquei… Aqui meu código:

recyclerView = view.findViewById(R.id.recyclerView);

FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();

//Query
Query query = firebaseFirestore.collection("HistoricoVendas");
//RecyclerOptions
FirestoreRecyclerOptions<Vendas> options = new FirestoreRecyclerOptions.Builder<Vendas>().setQuery(query, Vendas.class).build();
//Adapter
 adapter = new FirestoreRecyclerAdapter<Vendas, VendasViewHolder>(options) {
    @NonNull
    @Override
    public VendasViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_lista, parent, false);
         return new VendasViewHolder(view1);
    }

    @Override
    protected void onBindViewHolder(@NonNull VendasViewHolder holder, int position, @NonNull Vendas model) {

        holder.comprador.setText(model.getComprador());
        holder.equipamentoVendido.setText(model.getEquipamentoVendido());
        holder.valorTotal.setText(model.getValorTotal());
        holder.dataVenda.setText(model.getDataVenda());
        holder.mesDaVenda.setText(model.getMesVenda());
    }
};

 recyclerView.setHasFixedSize(true);
 recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
 recyclerView.setAdapter(adapter);


return view;

}
0

Bom, eu estou a dias tentando criar um recyclerView com seções usando o firebase mas nada funciona… Eu estou tentando fazer algo como, por exemplo, em Janeiro fica alguns itens, em Fevereiro outros e por ai vai. Eu consegui usar o firebase pra fazer o recyclerView e tudo mais, mas não faço ideia de como separar os dados daquela forma que expliquei… Aqui meu código:

recyclerView = view.findViewById(R.id.recyclerView);

FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();

//Query
Query query = firebaseFirestore.collection("HistoricoVendas");
//RecyclerOptions
FirestoreRecyclerOptions<Vendas> options = new FirestoreRecyclerOptions.Builder<Vendas>().setQuery(query, Vendas.class).build();
//Adapter
 adapter = new FirestoreRecyclerAdapter<Vendas, VendasViewHolder>(options) {
    @NonNull
    @Override
    public VendasViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_lista, parent, false);
         return new VendasViewHolder(view1);
    }

    @Override
    protected void onBindViewHolder(@NonNull VendasViewHolder holder, int position, @NonNull Vendas model) {

        holder.comprador.setText(model.getComprador());
        holder.equipamentoVendido.setText(model.getEquipamentoVendido());
        holder.valorTotal.setText(model.getValorTotal());
        holder.dataVenda.setText(model.getDataVenda());
        holder.mesDaVenda.setText(model.getMesVenda());
    }
};

 recyclerView.setHasFixedSize(true);
 recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
 recyclerView.setAdapter(adapter);


return view;

}

android – How do I prevent inconsistent transactions in Paypal transactions if the firebase update fails?

In my android app, I have implemented Paypal functionality with a firebase backend. I would like to update the firebase-end based on the result of a Paypal transaction. Basically, if the payment is successfull update some document on firebase indicating so. I worry that if I do not batch the Paypal transaction and the firebase operation, it could cause inconsistency if the firebase update fails. How can I handle this?

Angular table with data from Firebase not sorting?

I have finished creating the sort function and its directives which looked like this:

export type SortDirection = 'asc' | 'desc' | '';
const rotate: { (key: string): SortDirection } = { 'asc': 'desc', 'desc': '', '': 'asc' };
export const compare = (v1, v2) => v1 < v2 ? -1 : v1 > v2 ? 1 : 0;

export interface SortEvent {
  column: string;
  direction: SortDirection;
}

@Directive({
  selector: 'th(sortable)',
  host: {
    '(class.asc)': 'direction === "asc"',
    '(class.desc)': 'direction === "desc"',
    '(click)': 'rotate()'
  }
})

export class NgbdSortableHeader {
  
  @Input() sortable: string;
  @Input() direction: SortDirection = '';
  @Output() sort = new EventEmitter<SortEvent>();

  rotate() {
    console.log('Rotate');
    this.direction = rotate(this.direction);
    this.sort.emit({ column: this.sortable, direction: this.direction });
  }
}

export class ListCustomersComponent implements OnInit { 
  filterCustomers: Customers() = ();
  sortCustomers: Customers() = ();

//Sort purpose
@ViewChildren(NgbdSortableHeader) headers: QueryList<NgbdSortableHeader>;

  async getCustomers(token) {
    this.clearMessages();
    this.customersService.getCustomers(token).subscribe(result => {
      this.customers = result.filter(x => x.active); // display active customers only
      this.filterCustomers = this.customers;
      this.sortCustomers = this.customers;
      this.totalLengthOfCollection = this.filterCustomers.length;
      this.loadPage = true;
    }, err => {
      this.alert.code = err.error.error;
      if (this.alert.code == undefined) {
        this.alert.code = err.statusText;
        this.alert.message = 'Unexpected error encountered.';
        this.alert.status = 'failed';
        console.log(err);
      } else if (this.alert.code == "Unauthorized") {
        this.customersService.denyAccess();
      } else {
        this.alert.message = err.error.message;
        this.alert.status = 'failed';
      }
    });
  }

//Sort function
  public onSort({ column, direction }: SortEvent) {
    this.headers.forEach(header => {
      if (header.sortable !== column) {
        header.direction = '';
        console.log("hello hello");
      }
    });

    if (direction === '') {
      this.filterCustomers = this.customers;
      this.sortCustomers = this.customers;
      console.log("hello hello hello");
    } else {
      this.sortCustomers = ().sort((a, b) => {
        const res = compare(a(column), b(column));
        return direction === 'asc' ? res : -res;
      });
      this.filterCustomers = ().sort((a, b) => {
        const res = compare(a(column), b(column));
        return direction === 'asc' ? res : -res;
      });
    }
    
  }
}

But my html is not able to call the functions of the sort since it did not return a log on the console, is there something wrong with my html? Here is how my html table looks like:

 <thead>
   <tr class="text-center">
     <th scope="col" sortable="firstName" (sort)="onSort($event)" nowrap>Name</th>
     <th scope="col" sortable="mobileNumber" (sort)="onSort($event)" nowrap>Mobile Number</th>
     <th scope="col" sortable="email" (sort)="onSort($event)" nowrap>Email</th>
     <th scope="col" sortable="address" (sort)="onSort($event)" nowrap>Address</th>
     <th scope="col" nowrap>Action</th>
   </tr>
 </thead>

<tr class="text-center" *ngFor="let customer of filterCustomers | slice: (page-1) * pageSize : (page-1) * pageSize + pageSize; index as i">
     <td class="text-center" nowrap>
       <small>{{ customer.firstName + ' ' + customer.lastName }}</small>
     </td>
     <td class="text-center">
       <small>{{ customer.mobileNumber }}</small>
     </td>
     <td class="text-center">
       <small>{{ customer.email }}</small>
     </td>
     <td class="text-left">
       <small>{{ customer.address.city != '' && customer.address.city != null ? customer.address.city : '' }}{{ customer.address.province != '' && customer.address.province != null ? ', ' + customer.address.province :'' }}</small>
     </td>
</tr>

I think I need to correct my ngFor at the but I’m not sure how to call both the filterCustomers and sortCustomers together

firebase rules for Realtime Database

i have a db:

-users

--UserUid#1
---name:alex
---isUser:true
---isModer:false

--UserUid#2
---name:valder
---isUser:false
---isModer:true
---users
----UserUid#1:true

when user (isUser:true) register in the app he filling another user uid (which have a property isModer:true) and add self uid to his profile (UserUid#2 -> users -> UserUid#1:true).

I have trouble with security rules. As i understand any others who have my db name can edit db. So i found in docs an example

"rules": {
    "some_path": {
      "$uid": {
        ".read": true,
        // or ".read": "auth.uid != null" for only authenticated users
        ".write": "auth.uid == $uid"
      }
    }
  }

But i have a trouble: how to do that if user indicates in registration a some uid just him can edit this uid

java – ¿Como puedo hacer que mi app lea en segundo plano Realtime Database de Firebase y lanzar una notificación?

Estoy realizando una app que necesito que reciba notificaciones al realizar cambios en la BBDD. He intentado implementar código que he encontrado en esta web ¿Es posible recibir una notificación automática cuando se añada algo en la base de datos de Firebase? pero no me funciona.

Lanzando el servicio desde la actividad principal creo que accede con normalidad, pero modifico la BBDD y no recibo ninguna notificación ni con la app activa ni cerrada.

Es la primera vez que hago una app completa de forma individual y no consigo solucionar este problema, cualquier ayuda se agradece. Un saludo.

firestore – Deletar item de lista pelo flutter e firebase

Tenho uma lista de categorias e preciso deletar itens dessa lista.

Essa é a categoryTile.dart

import 'package:flutter/material.dart';
import 'package:note_study/model/category/category_manager.dart';
import 'package:note_study/model/category/category_model.dart';

class CategoryListTile extends StatefulWidget {
  CategoryListTile(this.categoryModel);
  final CategoryModel categoryModel;

  @override
  _CategoryListTileState createState() => _CategoryListTileState();
}

class _CategoryListTileState extends State<CategoryListTile> {
  CategoryManager categoryManager;
  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        categoryManager.deleteDataCategory();
      },
      child: Expanded(
        child: Container(
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              color: Theme.of(context).cursorColor),
          height: 50,
          margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 8),
          child: Center(
            child: Text(
              widget.categoryModel.name,
              style: TextStyle(
                  fontSize: 15,
                  fontWeight: FontWeight.bold,
                  color: Colors.white),
            ),
          ),
        ),
      ),
    );
  }
}

Essa é a categoryScreen.dart

import 'package:flutter/material.dart';
import 'package:note_study/model/category/category_manager.dart';
import 'package:note_study/screen/category/components/category_list_tile.dart';
import 'package:provider/provider.dart';

class CategoryScreen extends StatefulWidget {
  @override
  _CategoryScreenState createState() => _CategoryScreenState();
}

class _CategoryScreenState extends State<CategoryScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
      ),
      body: Consumer<CategoryManager>(
        builder: (_, categoryManager, __) {
          return GridView.builder(
            gridDelegate:
                SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
            itemCount: categoryManager.allCategory.length,
            itemBuilder: (context, index) {
              return CategoryListTile(categoryManager.allCategory(index));
            },
          );
        },
      ),
    );
  }
}

Essa é a categoryManager.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:note_study/model/category/category_model.dart';

class CategoryManager extends ChangeNotifier {
  CategoryManager() {
    loadAllCategory();
  }

  final Firestore firestore = Firestore.instance;
  final FirebaseAuth fireAuth = FirebaseAuth.instance;

  CategoryModel categoryModel;

  Future<void> saveDataCategory(
      {CategoryModel categoryModel,
      Function onSuccess,
      Function onFail}) async {
    try {
      this.categoryModel = categoryModel;
      await categoryModel.saveData();
      onSuccess();
    } on PlatformException catch (e) {
      onFail(print(e));
    }

    notifyListeners();
  }

  Future<void> deleteDataCategory() async {
    categoryModel.deleteData();

    notifyListeners();
  }

  List<CategoryModel> allCategory = ();

  Future<void> loadAllCategory({FirebaseUser fireUser}) async {
    final FirebaseUser currentUser = fireUser ?? await fireAuth.currentUser();
    firestore
        .collection('users')
        .document(currentUser.uid)
        .collection('category')
        .snapshots()
        .listen(
      (snapshot) {
        allCategory = snapshot.documents
            .map((d) => CategoryModel.fromDocument(d))
            .toList();
        notifyListeners();
      },
    );
    notifyListeners();
  }
}

E essa é a categoryModel.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:note_study/model/user/user_manager.dart';

class CategoryModel {
  CategoryModel({
    this.id,
    this.name,
  });
  UserManager userManager = UserManager();
  CategoryModel.fromDocument(DocumentSnapshot categorySnap) {
    id = categorySnap.documentID;
    name = categorySnap.data('name') as String;
  }
  String id;
  String name;
  //Pegando usuario logado
  String get idUSer => userManager.userModel.id;
  DocumentReference get firestoreRef =>
      Firestore.instance.document('users/$idUSer');

  Future<void> saveData() async {
    await firestoreRef.collection('category').add(toMap());
  }

  Future<void> deleteData() async {
    await firestoreRef.collection('category').document(id).delete();
  }

  Map<String, dynamic> toMap() {
    return {
      'name': name,
    };
  }
}

Preciso recuperar o index ou algo do tipo para poder deletar o documento correto.

Como faço?

android – Duda con Firebase

**Buenas, ¿Cómo va? Estoy creando mi primer proyecto con Firebase en Realtime Database. La verdad es que funciona bastante bien y se me ha generado una duda. Probé la aplicación en mi dispositivo y funció de maravilla, realizó el insert bien. Lo probé en otro dispositivó y también realizó el insert de manera correcta. Pero, acá viene lo que me genera una duda, cuando realicé el insert desde el segundo dispositivo en vez de crear otro hilo, sobre-escribió los primeros. A modo ilustrativo:

Insert com el primer dispositivo:

introducir la descripción de la imagen aquí

Insert con el segundo dispositivo:

introducir la descripción de la imagen aquí

Lo que quiero saber es si hay alguna forma de evitar que se sobre-escriban los valores. Básicamente, es como que hace un update, y lo que quiero es que se genere otro registro. ¿Es esto posible? Es mi primera vez usando Firebase y leyendo la documentación la verdad es que no he encontrado lo que busco

Así es como hago el Insert:

private void agregarUsuario() { //Método para Firebase
    String idUsuario = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
    Calendar c = Calendar.getInstance();
    String diaActual = c.get(Calendar.DAY_OF_MONTH) + "/" + c.get(Calendar.MONTH) + "/" + c.get(Calendar.YEAR);
    RegistroClase rc = new RegistroClase(
            idUsuario,
            diaActual,
            telefono.getText().toString()
    );

    firebase.setValue(rc);
}

Y lo meto dentro de un botón:

    registrar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            agregarUsuario();
        }
    });

Variables que uso:

private String FIREBASE_URL = "https://papri-af31b.firebaseio.com/";
private String FIREBASE_CHILD = "test";
Firebase firebase;

Actividad completa:

public class RegistroActivity extends AppCompatActivity {
    EditText telefono, imei;
    Button registrar;

    private String FIREBASE_URL = "https://papri-af31b.firebaseio.com/";
    private String FIREBASE_CHILD = "test";
    Firebase firebase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registro);

        ButterKnife.bind(this);
        Firebase.setAndroidContext(this);
        firebase = new Firebase(FIREBASE_URL).child(FIREBASE_CHILD);

        telefono = (EditText)findViewById(R.id.etTeléfono);
        imei = (EditText)findViewById(R.id.etIMEI);

        String idUsuario = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        imei.setText(idUsuario);

        registrar = (Button)findViewById(R.id.btnRegistrar);
        registrar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                agregarUsuario();
            }
        });
    }

    private void agregarUsuario() { //Método para Firebase
        String idUsuario = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.ANDROID_ID);
        Calendar c = Calendar.getInstance();
        String diaActual = c.get(Calendar.DAY_OF_MONTH) + "/" + c.get(Calendar.MONTH) + "/" + c.get(Calendar.YEAR);
        RegistroClase rc = new RegistroClase(
                idUsuario,
                diaActual,
                telefono.getText().toString()
        );
        firebase.setValue(rc);
    }
}

reactjs – How to update real time database from Firebase ? – React Native app

import React from 'react';
import { Button, View, Text } from 'react-native';
import Firebase from '../configFirebase';

class UpDownButton extends React.Component {

    constructor(props) {
      super(props);

      this.state = {};
    }

    componentDidMount() {
        const ref = Firebase.database().ref('children/');
    
        ref.on('value', (snapshot) => {
          this.setState({
            element: snapshot.val()
          })
        });
    }

    Move(arr, old_index, new_index) {
        
        if (new_index >= arr.length) {
            var k = new_index - arr.length + 1;
        }
        arr.splice(new_index, 0, arr.splice(old_index, 1)(0));
        return arr; 
    }
        

    UpItem = () => {
        const arr = this.state.element;
        const old_index = arr.findIndex(x => x._uid ==="12345");
        const new_index = old_index - 1

        this.setState(this.Move(arr, old_index, new_index))

    }

    DownItem = () => {
        const arr = this.state.element;
        const old_index = arr.findIndex(x => x._uid ==="12345");
        const new_index = old_index + 1

        this.setState(this.Move(arr, old_index, new_index))

    }


    render() {

        console.log(this.state.element);

        return (
        <View>
            <Button 
            title="Click to increment by 1"
            onPress={this.UpItem}/>

            <Button 
            title="Click to decrease by 1"
            onPress={this.DownItem}/>
        </View>
        );
    }


  }

  export default UpDownButton;