Android Studio Java Firebase - firebase

String uid;
FirebaseUser user;
TextView BalanceTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_miner);
fAuth = FirebaseAuth.getInstance();
BalanceTV = (TextView)findViewById(R.id.BalanceTV);
uid = FirebaseAuth.getInstance().getCurrentUser().getUid()
final String Balance = BalanceTV.getText().toString();
BalanceTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
databaseReference = FirebaseDatabase.getInstance().getReference("users");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
if(snapshot.getKey().matches("HKAD9FBFfqalSeXCliGTNHPp6Bf1")) {
Map map = (Map) snapshot.getValue();
BalanceTV.setText(map.get("Balance").toString());
}
}
like why when i change "HKAD9FBFfqalSeXCliGTNHPp6Bf1" which is the user id of the user in firebase to uid which is user id i don't retrieve the info of balance, but when i set it to "HKAD9FBFfqalSeXCliGTNHPp6Bf1" i get the balance?
https://i.stack.imgur.com/uXn7n.png

Related

Firebase image delete

I'm building a gallery app with firebase.
My problem is that when I delete the image, it deletes the document from firebase, but it does not delete it from the screen and the other images are copied on the screen, I could not handle it, I will show you the example below.
THİS GALLERY ADAPTER
#Override
public void onBindViewHolder(#NonNull GalleryHolder holder, int position) {
Picasso.get().load(galleryAdapterArrayList.get(position).downloadUrl).into(holder.imageView);
}
public class GalleryHolder extends RecyclerView.ViewHolder{
public Gallery gallery;
public CheckBox checkBox;
ImageView imageView;
public FirebaseFirestore firebaseFirestore;
public FirebaseUser firebaseUser;
public FirebaseAuth firebaseAuth;
public String Docıd;
public DocumentSnapshot snapshot;
public CollectionReference collectionReference;
public GalleryHolder(#NonNull View itemview) {
super(itemview);
imageView=itemview.findViewById(R.id.gallerLayoutimageview);
firebaseFirestore=FirebaseFirestore.getInstance();
firebaseAuth=FirebaseAuth.getInstance();
firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
itemview.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
PopupMenu popupMenu=new PopupMenu(v.getContext(),v);
popupMenu.setGravity(Gravity.END);
popupMenu.getMenu().add(R.string.sil).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem menuItem) {
DocumentReference documentReference=firebaseFirestore.collection("Gallery").document(firebaseUser.getUid()).collection("myGallery").document(galleryAdapterArrayList.get(getPosition()).docId);
documentReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
System.out.println("dsadad");
notifyDataSetChanged();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(v.getContext(),R.string.notSilinmedi,Toast.LENGTH_SHORT);
}
});
return false;
}
});
popupMenu.show();
return false;
}
});
}
}
}
THİS GALLERY ACTIVITY
public void getData() {
firebaseFirestore.collection("Gallery").document(firebaseUser.getUid()).collection("myGallery").orderBy("date", Query.Direction.DESCENDING).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if (error != null) {
Toast.makeText(getApplicationContext(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
if (value != null) {
for (DocumentSnapshot snapshot : value.getDocuments()) {
Map<String, Object> data = snapshot.getData();
String downloadUrl = (String) data.get("downloadUrl");
String docId = (String) data.get("docId");
checkBox=findViewById(R.id.checkimages);
GalleryModel galleryModel=new GalleryModel(docId,downloadUrl,checkBox);
galleryModelArrayList.add(galleryModel);
}
galleryAdapter.notifyDataSetChanged();
}
}
});
}
before deleting images
after deleting images
Reset activity

FirebaseAuth.getInstance().getCurrentUser().getUid() always pointing to same ID

I'm trying to make a feature in my Android studio app which allows users to book appointment with a fixed list of doctors through Firebase realtime database. The problem is that FirebaseAuth.getInstance().getCurrentUser().getUid() is always pointing to same ID and so instead of new appointment details being added via children nodes in the parent node, the existing details in children nodes are being overwritten. Here's my code-
DoctorList.java-
public class DoctorList extends AppCompatActivity {
TextView doc1,doc2,doc3,doc4;
FirebaseAuth mAuth;
DatabaseReference patUser;
ProgressDialog loader;
FirebaseDatabase database= FirebaseDatabase.getInstance();
String Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_list);
Intent intent = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
String email = intent.getStringExtra("message_key");//patient email
doc1=findViewById(R.id.doc1);
doc2=findViewById(R.id.doc2);
doc3=findViewById(R.id.doc3);
doc4=findViewById(R.id.doc4);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user= mAuth.getInstance().getCurrentUser();
patUser= database.getReference().child("Patient Appointments");
doc1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loader.setMessage("Please wait....");
loader.setCanceledOnTouchOutside(false);
loader.show();
Intent intent= new Intent( DoctorList.this, Book.class);
intent.putExtra("message_key1", "elise#doc.com");
intent.putExtra("message_key2", email);
startActivity(intent);
// create the get Intent object
Intent intent1 = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
Date = intent1.getStringExtra("message");
//Toast.makeText(PatientPage.this, str, Toast.LENGTH_SHORT).show();
String currentUserId = mAuth.getCurrentUser().getUid();
patUser= database.getReference().child("Patient Appointments").child(currentUserId);
//HashMap userInfo = new HashMap();
HashMap userInfo = new HashMap();
userInfo.put("Date",Date);
userInfo.put("Patient",email);
userInfo.put("Doctor","Dr.Elise Heather");
userInfo.put("Phone","5925866");
userInfo.put("Status","Pending");
patUser.updateChildren(userInfo).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()){
Toast.makeText(DoctorList.this, "Little more to go....", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(DoctorList.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
loader.dismiss();
//Intent intent2= new Intent( DoctorList.this, PatientPage.class);
//startActivity(intent2);
}
});
}
}
Book.java-
public class Book extends AppCompatActivity {
TextView selectedDate;
Button calenderButton,ok;
FirebaseAuth mAuth;
DatabaseReference docUser;
ProgressDialog loader;
FirebaseDatabase database= FirebaseDatabase.getInstance();
String Date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
Intent intent = getIntent();
// receive the value by getStringExtra() method
// and key must be same which is send by first
// activity
String docEmail = intent.getStringExtra("message_key1");
String patEmail = intent.getStringExtra("message_key2");
selectedDate=findViewById(R.id.text);
calenderButton=findViewById(R.id.calender);
ok=findViewById(R.id.ok);
loader = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user= mAuth.getInstance().getCurrentUser();
docUser= database.getReference().child("Doctor Schedule");
MaterialDatePicker materialDatePicker=MaterialDatePicker.Builder.datePicker().
setTitleText("Select date").setSelection(MaterialDatePicker.todayInUtcMilliseconds()).build();
calenderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
materialDatePicker.show(getSupportFragmentManager(),"Tag_Picker");
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
selectedDate.setText(materialDatePicker.getHeaderText());
Date=materialDatePicker.getHeaderText();
}
});
}
});
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Date != null) {
String currentUserId = mAuth.getCurrentUser().getUid();
docUser = database.getReference().child("Doctor Schedule").child(currentUserId);
//HashMap userInfo = new HashMap();
HashMap userInfo = new HashMap();
userInfo.put("Date", Date);
userInfo.put("Patient", patEmail);
userInfo.put("Doctor", docEmail);
userInfo.put("Status", "Pending");
docUser.updateChildren(userInfo).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Toast.makeText(Book.this, "Appointment booked", Toast.LENGTH_SHORT).show();
Intent intent= new Intent( Book.this, DoctorList.class);
intent.putExtra("message", Date);
startActivity(intent);
} else {
Toast.makeText(Book.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(Book.this, "Select date!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Suppose a user with email athy#gmail.com books appointment and in Firebase database there's already details of booking by another user nivi#gm.com . Then the details of the latter user in the parent node (ID) gets overwritten by user athy#gmail.com and it looks like this. I don't think I've written code for overwriting instead of updating since it works fine in other Android studio projects, so I'm guessing FirebaseAuth.getInstance().getCurrentUser().getUid() is the one always pointing to same ID which I've circled in the image.
How do I fix this?

Post value to server when no internet connection android studio

I'm trying to send a value to the server when the connection doesn't exist, when it connects to the internet it runs fine and is saved to the server and sqlite. but the problem arises when switching state from offline to online. I send one value to the server when the connection is offline but when the state moves to online the value I sent earlier becomes multiple on the server while in the sqlite database only one value is stored.
this is my network state checker class
public class NetworkStateCheckerNama extends BroadcastReceiver {
//context and database helper object
private Context context;
private Database db;
ApiRequestData apiRequestData;
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
apiRequestData = ServiceGenerator.createBaseService(this.context, ApiRequestData.class);
db = new Database(context);
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
//if there is a network
if (activeNetwork != null) {
//if connected to wifi or mobile data plan
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
//getting all the unsynced user
Cursor cursor2 = db.getUnsyncedNama();
if (cursor2.moveToFirst()) {
do {
//calling the method to save the unsynced name to MySQL
Nama(
cursor2.getString(cursor2.getColumnIndexOrThrow(Database.KOLOM_NAMA_COBA)),
cursor2.getString(cursor2.getColumnIndexOrThrow(Database.KOLOM_NIP_COBA))
);
} while (cursor2.moveToNext());
}
}
}
}
private void Nama(final String nama,final String nip) {
//Call call = retrofit.create(APIInterface.class).saveName(name);
Call call = apiRequestData.nama_query(nama,nip);
call.enqueue(new Callback<Responses>() {
#Override
public void onResponse(Call<Responses> call, Response<Responses> response) {
if (response.code() == 200){
db.updateNamaStatus(nip, MainActivity.NAME_SYNCED_WITH_SERVER);
//sending the broadcast to refresh the list
context.sendBroadcast(new Intent(MainActivity.DATA_SAVED_BROADCAST_MAIN));
}
}
#Override
public void onFailure(Call<Responses> call, Throwable t) {
}
});
}
this is my MainActivity Class
public class MainActivity extends AppCompatActivity {
Session session;
Button buttonLogout,buttonKirim;
TextView textViewNamaMain, textViewNipMain;
EditText editTextNamaMain;
Database database;
private AdapterNama mAdapter;
private RecyclerView listviewNama;
ApiRequestData apiRequestData;
//1 means data is synced and 0 means data is not synced
public static final int NAME_SYNCED_WITH_SERVER = 1;
public static final int NAME_NOT_SYNCED_WITH_SERVER = 0;
//a broadcast to know weather the data is synced or not
public static final String DATA_SAVED_BROADCAST_MAIN = "com.example.myapplication.datasave2";
ArrayList<Nama> namaArray;
ArrayList<User> users;
BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new Session(this);
buttonLogout = findViewById(R.id.buttonLogout);
buttonKirim = findViewById(R.id.buttonKirim);
textViewNipMain = findViewById(R.id.textViewNipMain);
textViewNamaMain = findViewById(R.id.textViewNamaMain);
editTextNamaMain = findViewById(R.id.editTextTextNamaMain);
String nip = getIntent().getStringExtra("nip");
listviewNama = findViewById(R.id.lv_nama);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
listviewNama.setLayoutManager(layoutManager);
listviewNama.setItemAnimator(new DefaultItemAnimator());
database = new Database(this);
namaArray = new ArrayList<>();
users = new ArrayList<>();
apiRequestData = ServiceGenerator.createBaseService(this, ApiRequestData.class);
textViewNipMain.setText(nip);
registerReceiver(new NetworkStateCheckerNama(), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
loadDaftarNama(nip);
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//loading the names again
loadDaftarNama(nip);
}
};
registerReceiver(broadcastReceiver, new IntentFilter(DATA_SAVED_BROADCAST_MAIN));
if(!session.isUserLogin()){
logout();
}
buttonKirim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpanKeServer();
}
});
buttonLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logout();
}
});
users.clear();
Cursor cursor = database.getUsersWhereNip(nip);
if (cursor.moveToFirst()) {
do {
User user = new User(
cursor.getString(cursor.getColumnIndexOrThrow(Database.KOLOM_NIP)),
cursor.getString(cursor.getColumnIndexOrThrow(Database.KOLOM_NAMA)),
cursor.getString(cursor.getColumnIndexOrThrow(Database.KOLOM_PASSWORD)),
cursor.getInt(cursor.getColumnIndexOrThrow(Database.KOLOM_STATUS))
);
users.add(user);
textViewNamaMain.setText(user.getNama());
} while (cursor.moveToNext());
}
}
private void SimpanKeServer(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Saving Name...");
progressDialog.show();
String nama = editTextNamaMain.getText().toString();
String nip = textViewNipMain.getText().toString();
Call call = apiRequestData.nama_query(nama,nip);
call.enqueue(new Callback<Responses>() {
#Override
public void onResponse(Call<Responses> call, Response<Responses> response) {
progressDialog.dismiss();
if(response.code() == 200){
//if there is a success
//storing the name to sqlite with status synced
SaveNamaToLocal(nama,nip,NAME_SYNCED_WITH_SERVER);
Toast.makeText(MainActivity.this, "Berhasil", Toast.LENGTH_SHORT).show();
}else {
progressDialog.dismiss();
//if there is some error
//saving the name to sqlite with status unsynced
SaveNamaToLocal(nama,nip,NAME_NOT_SYNCED_WITH_SERVER);
Toast.makeText(MainActivity.this, "Gagal", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Responses> call, Throwable t) {
progressDialog.dismiss();
SaveNamaToLocal(nama,nip,NAME_NOT_SYNCED_WITH_SERVER);
Toast.makeText(MainActivity.this, "Gagal", Toast.LENGTH_SHORT).show();
}
});
}
private void SaveNamaToLocal(String nama, String nip, int status){
database.Nama(nama,nip,status);
Nama namas = new Nama(nama,nip,status);
namaArray.add(namas);
refreshList();
}
private void loadDaftarNama(String nip) {
namaArray.clear();
Cursor cursor = database.getNama(nip);
if (cursor.moveToFirst()) {
do {
Nama nama = new Nama(
cursor.getString(cursor.getColumnIndexOrThrow(Database.KOLOM_NAMA_COBA)),
cursor.getString(cursor.getColumnIndexOrThrow(Database.KOLOM_NIP_COBA)),
cursor.getInt(cursor.getColumnIndexOrThrow(Database.KOLOM_STATUS_NAMA_COBA))
);
namaArray.add(nama);
} while (cursor.moveToNext());
}
mAdapter = new AdapterNama(this, namaArray);
listviewNama.setAdapter(mAdapter);
}
#SuppressLint("NotifyDataSetChanged")
private void refreshList() {
mAdapter.notifyDataSetChanged();
}
private void logout(){
session.updateUserLoginStatus(false);
finish();
startActivity(new Intent(MainActivity.this,LoginActivity.class));
}
}
this when online
enter image description here
enter image description here
this the problem when state internet switch from offline to online
enter image description here
enter image description here
Even in server send 3 same values
I'm sorry for my english and my question structure im new in programmer, and thank you for the answer

How do I change the value of child in firebase using a checkbox click

This is the code am using to fetch data from my firebase realtime database.
private void fetch() {
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("products");
FirebaseRecyclerOptions<Product> options =
new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(query, new SnapshotParser<Product>() {
#NonNull
#Override
public Product parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Product(snapshot.child("id").getValue().toString(),
snapshot.child("name").getValue().toString(),
snapshot.child("price").getValue().toString(),
snapshot.child("sku").getValue().toString(),
snapshot.child("category").getValue().toString(),
snapshot.child("subCategory").getValue().toString(),
snapshot.child("availability").getValue().toString());
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Product, ProductsViewHolder>(options) {
#Override
public ProductsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_product, parent, false);
return new ProductsViewHolder(view);
}
#Override
protected void onBindViewHolder(ProductsViewHolder holder, final int position, final Product model) {
holder.setName(model.getName());
holder.setPrice(model.getPrice());
holder.setSubCategory(model.getSubCategory());
holder.setViewAvailability(model.getAvailability());
//holder.setSku(model.getSku());
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(ProductsActivity.this, model.getId(), Toast.LENGTH_SHORT).show();
}
});
}
};
recyclerView.setAdapter(adapter);
}
This is the product viewHolder
public class ProductsViewHolder extends RecyclerView.ViewHolder{
public CardView root;
public TextView viewSubCategory;
public TextView viewName;
public TextView viewPrice;
//public TextView viewSku;
public CheckBox viewAvailability;
Context context;
public ProductsViewHolder(View itemView) {
super(itemView);
root = itemView.findViewById(R.id.list_product_root);
viewSubCategory = itemView.findViewById(R.id.viewSubCategory);
viewName = itemView.findViewById(R.id.viewName);
viewPrice = itemView.findViewById(R.id.viewPrice);
viewAvailability = itemView.findViewById(R.id.viewAvailability);
//viewAvailability.setOnCheckedChangeListener(this);
}
public void setName(String string) {
viewName.setText(string);
}
public void setViewAvailability(String string) {
if (string.equals("0")){
viewAvailability.setChecked(false);
}else {
viewAvailability.setChecked(true);
}
}
public void setPrice(String string) {
viewPrice.setText(String.format("%,d", Integer.parseInt(string)));
}
/* public void setSku(String string) {
viewSku.setText(string);
}*/
public void setSubCategory(String string) {
viewSubCategory.setText(string);
}
}
veiwAvailaibility is a checkbox, that when checked it should change the value of availability (which is a child of a product) in firebase from 0 to 1 (checked and unchecked respectively). I am failing to get the clicking checking functionality done in the ViewHolder or in my fetch class. Any assistance is appreciated.
private void fetch() {
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("products");
FirebaseRecyclerOptions<Product> options =
new FirebaseRecyclerOptions.Builder<Product>()
.setQuery(query, new SnapshotParser<Product>() {
#NonNull
#Override
public Product parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Product(snapshot.child("id").getValue().toString(),
snapshot.child("name").getValue().toString(),
snapshot.child("price").getValue().toString(),
snapshot.child("sku").getValue().toString(),
snapshot.child("category").getValue().toString(),
snapshot.child("subCategory").getValue().toString(),
snapshot.child("availability").getValue().toString());
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Product, ProductsViewHolder>(options) {
#Override
public ProductsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_product, parent, false);
return new ProductsViewHolder(view);
}
#Override
protected void onBindViewHolder(ProductsViewHolder holder, final int position, final Product model) {
holder.setName(model.getName());
holder.setPrice(model.getPrice());
holder.setSubCategory(model.getSubCategory());
holder.setViewAvailability(model.getAvailability());
holder.viewAvailability.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked){
//suggestion.setSelected(true);
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("products").child(model.getId());
Map<String, Object> updates = new HashMap<String,Object>();
updates.put("availability", "1");
ref.updateChildren(updates);
}else {
//suggestion.setSelected(false);
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("products").child(model.getId());
Map<String, Object> updates = new HashMap<String,Object>();
updates.put("availability", "0");
ref.updateChildren(updates);
}
}
});
//holder.setSku(model.getSku());
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
};
recyclerView.setAdapter(adapter);
}

Using database on recyclerview

The first activity save some data at the firebase database and i need to show on the second activity using a recyclerview. I'm trying many times and i follow a tutorial, but always the recyclerview isn't displaying anything.
The Firebase was working correctly saving the data, but i can't put at recyclerview.
The activities are:
MenuActivity (recyclerview)
private RecyclerView recyclerView;
private Informações informações;
FirebaseDatabase database;
DatabaseReference myRef;
List<Informações> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Informações");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list = new ArrayList<Informações>();
for (DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
Informações value = dataSnapshot1.getValue(Informações.class);
Informações informações = new Informações();
String empresa = value.getEmpresa();
String setor = value.getSetor();
String data = value.getData();
informações.setEmpresa(empresa);
informações.setSetor(setor);
informações.setData(data);
list.add(informações);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(list, MenuActivity.this);
RecyclerView.LayoutManager recyce = new GridLayoutManager(MenuActivity.this,2);
recyclerView.setLayoutManager(recyce);
recyclerView.setAdapter(recyclerAdapter);
The RecyclerAdapter
List<Informações> list;
Context context;
public RecyclerAdapter(List<Informações> list, Context context){
this.list = list;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.adapter_lista,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder( MyViewHolder holder, int position) {
Informações mylist = list.get( position );
holder.empresa.setText(mylist.getEmpresa());
holder.setor.setText(mylist.getSetor());
holder.data.setText(mylist.getData());
}
#Override
public int getItemCount() {
int arr = 0;
try {
if (list.size() == 0)
{ arr = 0;
} else { arr = list.size(); }
} catch (Exception e) {}
return arr;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView empresa, setor, data;
public MyViewHolder(View itemView) {
super(itemView);
empresa = (TextView) itemView.findViewById(R.id.textEmpresa);
setor = (TextView) itemView.findViewById(R.id.textSetor);
data = (TextView) itemView.findViewById(R.id.textData);
}
}
}
And the Firebase
public class Informações {
private String equipe;
private String empresa;
private String setor;
private String responsavel;
private String visita;
private String ferramenta;
private String data;
public Informações() {
}
public void salvar(){
DatabaseReference firebase = ConfiguracaoFirebase.getFirebaseDatabase();
firebase.child("Informações")
.child( this.empresa )
.setValue( this );
}
public String getVisita() { return visita; }
public void setVisita(String visita) { this.visita = visita; }
public String getFerramenta() { return ferramenta; }
public void setFerramenta(String ferramenta) { this.ferramenta = ferramenta; }
public String getData() { return data; }
public void setData(String data) { this.data = data; }
public String getEquipe() { return equipe; }
public void setEquipe(String equipe) { this.equipe = equipe; }
public String getEmpresa() { return empresa; }
public void setEmpresa(String empresa) { this.empresa = empresa; }
public String getSetor() { return setor; }
public void setSetor(String setor) { this.setor = setor; }
public String getResponsavel() { return responsavel; }
public void setResponsavel(String responsavel) { this.responsavel = responsavel; }
}

Resources