I am developing a bus booking app. But I have a problem with the update and delete function. I am able to update the timings and price. But whenever I try to update the source or destination or bus number...my app gets stuck. When I checked my Firebase realtime database....it looks as if the value is stuck in an infinite loop...as the updated value...keeps getting changed from the old to the new value and new value to the old value continuously. This is causing my app to get stuck. I have two files with regard to this.
EditBus.java
package com.example.busticketbooking;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.HashMap;
import java.util.Map;
public class Edit_Bus extends AppCompatActivity {
//Variables
public EditText busNumEdit,srcEdit,destEdit,timingsEdit,priceEdit;
private DatabaseReference databaseReference;
public String BusID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_bus);
busNumEdit =findViewById(R.id.BusNumber);
srcEdit=findViewById(R.id.source);
destEdit=findViewById(R.id.dest);
timingsEdit=findViewById(R.id.timings);
priceEdit=findViewById(R.id.price);
Button deleteButton = findViewById(R.id.deletebtn);
Button updateButton = findViewById(R.id.updatebtn);
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
BusRVModel busRVModel = getIntent().getParcelableExtra("Bus");
if(busRVModel !=null){
busNumEdit.setText(busRVModel.getBusNum());
srcEdit.setText(busRVModel.getSrc());
destEdit.setText(busRVModel.getDest());
timingsEdit.setText(busRVModel.getTimings());
priceEdit.setText(busRVModel.getPrice());
BusID= busRVModel.getBusID();
}
databaseReference= firebaseDatabase.getReference("Bus").child(BusID);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String busNumVar= busNumEdit.getText().toString();
String srcVar=srcEdit.getText().toString();
String destVar=destEdit.getText().toString();
String timingsVar=timingsEdit.getText().toString();
String priceVar=priceEdit.getText().toString();
Map<String,Object> map=new HashMap<>();
map.put("busNum", busNumVar);
map.put("src",srcVar);
map.put("dest",destVar);
map.put("timings",timingsVar);
map.put("price",priceVar);
map.put("busID",BusID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
databaseReference.updateChildren(map);
Toast.makeText(Edit_Bus.this, "Bus updated", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Edit_Bus.this,MainActivity2.class));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Edit_Bus.this, "Update Error", Toast.LENGTH_SHORT).show();
}
});
}
});
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteBus();
}
});
}
private void deleteBus(){
databaseReference.removeValue();
Toast.makeText(this, "Bus Deleted!!!", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Edit_Bus.this,MainActivity2.class));
}
}
BusRVModel.java
package com.example.busticketbooking;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class BusRVModel implements Parcelable{
private String busNum;
private String src;
private String dest;
private String timings;
private String price;
private String BusID;
public BusRVModel() {
}
public BusRVModel(String busNum, String src, String dest, String timings, String price, String busID ) {
this.busNum = busNum;
this.src = src;
this.dest = dest;
this.timings = timings;
this.price = price;
BusID = busID;
}
protected BusRVModel(Parcel in) {
busNum = in.readString();
src = in.readString();
dest = in.readString();
timings = in.readString();
price = in.readString();
BusID = in.readString();
}
public static final Creator<BusRVModel> CREATOR = new Creator<BusRVModel>() {
#Override
public BusRVModel createFromParcel(Parcel in) {
return new BusRVModel(in);
}
#Override
public BusRVModel[] newArray(int size) {
return new BusRVModel[size];
}
};
public String getBusNum() {
return busNum;
}
public void setBusNum(String busNum) {
this.busNum = busNum;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
public String getDest() {
return dest;
}
public void setDest(String dest) {
this.dest = dest;
}
public String getTimings() {
return timings;
}
public void setTimings(String timings) {
this.timings = timings;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getBusID() {
return BusID;
}
public void setBusID(String busID) {
BusID = busID;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(busNum);
parcel.writeString(src);
parcel.writeString(dest);
parcel.writeString(timings);
parcel.writeString(price);
parcel.writeString(BusID);
}
}
AddBus.java
package com.example.busticketbooking;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class Add_Bus extends AppCompatActivity {
private EditText busNum,src,dest,timings,price;
private Button button;
private FirebaseDatabase firebaseDatabase;
private DatabaseReference databaseReference;
private String BusID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_bus);
busNum=findViewById(R.id.BusNumber);
src=findViewById(R.id.source);
dest=findViewById(R.id.dest);
timings=findViewById(R.id.timings);
price=findViewById(R.id.price);
button=findViewById(R.id.btn);
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference("Bus");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String busNumVar=busNum.getText().toString();
String srcVar=src.getText().toString();
String destVar=dest.getText().toString();
String timingsVar=timings.getText().toString();
String priceVar=price.getText().toString();
BusID=busNumVar;
BusRVModel busRVModel=new BusRVModel(busNumVar,srcVar,destVar,timingsVar,priceVar,BusID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
databaseReference.child(BusID).setValue(busRVModel);
Toast.makeText(Add_Bus.this, "Bus added", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Add_Bus.this,MainActivity2.class));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Add_Bus.this, "Error is: "+error.toString(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
The problem is here:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
databaseReference.updateChildren(map);
Toast.makeText(Edit_Bus.this, "Bus updated", Toast.LENGTH_SHORT).show();
startActivity(new Intent(Edit_Bus.this,MainActivity2.class));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Edit_Bus.this, "Update Error", Toast.LENGTH_SHORT).show();
}
});
You're adding a listener to the database by calling addValueEventListener, which is documented as:
This method is triggered once when the listener is attached and again every time the data, including children, changes.
Now inside the onDataChange you modify the data at databaseReference, and as the documentation says that leads to onDataChange being called again, which leads to you updating the data again, which leads to...
Since it seems you only want to update the data once, you can use addListenerForSingleValueEvent to prevent retriggering onDataChange:
// 👇
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
...
Related
I have included a chatting feature in my app using Firebase realtime Database.
I want to be able to show notification when another user sends a message even when the app is turned but I'm not sure how
package com.example.android.crazytenmessenger;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.android.crazytenmessenger.auth.UserProfileActivity;
import com.example.android.crazytenmessenger.dao.MessageDAOHelper;
import com.example.android.crazytenmessenger.utils.DateUtils;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.ArrayList;
import java.util.List;
public class MessagingActivity extends AppCompatActivity {
private ListView listView;
private FloatingActionButton sendButton;
private EditText messageEditTextBox;
private ProgressBar progressBar;
private ImageView imagePicker;
private static final String TAG=MessagingActivity.class.getSimpleName();
private static final int MAX_WORD_LIMIT = 1000;
private DatabaseReference messageDatabaseReference;
private FirebaseStorage firebaseStorage;
private StorageReference chatPhotoStorageReference;
private ChildEventListener childEventListener;
private List<Message> messages;
private SharedPreferences sharedPreferences;
private String username;
private MessageDAOHelper daoHelper;
private MessageAdapter messageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messaging);
listView=(ListView) findViewById(R.id.message_list_view);
messageEditTextBox=(EditText) findViewById(R.id.message_box);
sendButton=(FloatingActionButton) findViewById(R.id.send_button);
imagePicker=(ImageView) findViewById(R.id.image_picker);
progressBar=(ProgressBar) findViewById(R.id.progress_Bar);
daoHelper=new MessageDAOHelper();
messageDatabaseReference=daoHelper.getMessageDatabaseReference();
firebaseStorage=FirebaseStorage.getInstance();
chatPhotoStorageReference=firebaseStorage.getReference().child("chat_photos");
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
messages=new ArrayList<>();
loadPreviousMessages();
messageAdapter=new MessageAdapter(this,R.layout.item_message,messages);
listView.setAdapter(messageAdapter);
username=FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
ActivityResultLauncher<String> mGetContent=registerForActivityResult(new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
uploadPhoto(result);
}
});
childEventListener=new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
Message currentMsg=snapshot.getValue(Message.class);
messageAdapter.add(currentMsg);
listView.smoothScrollToPosition(messageAdapter.getCount());
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) { }
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
Snackbar.make(findViewById(android.R.id.content),"succesfully removed", BaseTransientBottomBar.LENGTH_SHORT).show();
Log.v(TAG,"Removed : "+snapshot.getValue());
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) { }
#Override
public void onCancelled(#NonNull DatabaseError error) { }
};
messageEditTextBox.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().trim().length()>0)
sendButton.setEnabled(true);
else
sendButton.setEnabled(false);
}
#Override
public void afterTextChanged(Editable s) { }
});
messageEditTextBox.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_WORD_LIMIT)});
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username=sharedPreferences.getString(getString(R.string.my_profile_username_key),"USER");
username=FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
String timeStamp= DateUtils.getCurrentTimestamp();
Message message=new Message(messageEditTextBox.getText().toString(),username, null, timeStamp);
daoHelper.addMessage(message).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Snackbar.make(findViewById(android.R.id.content),"Message Not Sent "+e.getMessage(), BaseTransientBottomBar.LENGTH_SHORT).show();
}
});
messageEditTextBox.setText("");
}
});
imagePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGetContent.launch("image/*");
}
});
messageDatabaseReference.addChildEventListener(childEventListener);
}
/**
* Signing in the the current user automatically using OnStart
* Using Firebase Auth getCurrentUser
*/
#Override
protected void onStart() {
super.onStart();
String user= FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
if(user==null)
user="";
Snackbar.make(findViewById(android.R.id.content),"Welcome "+user,BaseTransientBottomBar.LENGTH_SHORT).show();
}
public void uploadPhoto(Uri uri){
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.setTitle("Uploading Image.....");
progressDialog.show();
StorageReference photoRef=chatPhotoStorageReference.child(uri.getLastPathSegment());
photoRef.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> result=taskSnapshot.getMetadata().getReference().getDownloadUrl();
progressDialog.dismiss();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String timeStamp=DateUtils.getCurrentTimestamp();
Message newMessage=new Message(null,username,uri.toString(), timeStamp);
daoHelper.addMessage(newMessage);
}
});
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double percentage=(100.00*snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
Log.v(TAG,"Progress : "+percentage);
progressDialog.setMessage("Progress : "+(int)percentage+"%");
}
});
Toast.makeText(this,"Image uploaded",Toast.LENGTH_SHORT).show();
}
private void deleteAllMessages(){
AlertDialog dialog=new AlertDialog.Builder(this)
.setTitle("Delete all messages")
.setMessage("Are you sure you want to delete all messages")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Deleting... ",Toast.LENGTH_SHORT).show();
messageDatabaseReference.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
chatPhotoStorageReference.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(),"All files Deleted ",Toast.LENGTH_SHORT).show();
messages.clear();
messageAdapter.notifyDataSetChanged();
listView.setAdapter(messageAdapter);
loadPreviousMessages();
}
});
}
})
.setNegativeButton(android.R.string.no,null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
private void loadPreviousMessages(){
messageDatabaseReference.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if(!task.isSuccessful())
Log.e(TAG,"Error in retrieving data ",task.getException());
else{
int count= (int) task.getResult().getChildrenCount();
if(count==0){
Snackbar.make(findViewById(android.R.id.content),
"Let's start chatting",
BaseTransientBottomBar.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
return;
}
progressBar.setVisibility(View.GONE);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id=item.getItemId();
if(id==R.id.profile_menu){
Intent intent=new Intent(MessagingActivity.this, UserProfileActivity.class);
startActivity(intent);
}else if(id==R.id.delete_all_option){
deleteAllMessages();
}else if(id==R.id.signout){
signoutCurrentUser();
}
return super.onOptionsItemSelected(item);
}
private void signoutCurrentUser() {
FirebaseAuth.getInstance().signOut();
finish();
}
}
I used child event listeners on firebase database reference to know the message sent but how to use it for notification.
You should use FCM for targeting the notification.
Whenever a message is sent(data inserted in the Firebase DB) you need to pull the data from DB and send a notification to the particular device using registration ID of the device.
The FCM notifaction should be a data type(user defined payload) if you wish your app to receive notification even when the app is in background or closed.
You can use Notification Type (the object holds "notification" as Key), this will work only when the app is in foreground.
Take a look at this
https://firebase.google.com/docs/cloud-messaging/concept-options
You can not show it through your app. It is system feature.
https://firebase.google.com/docs/cloud-messaging/concept-options
your json body should include
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}
I am totally new to Android Studio.
I created recycleview for Budgeting. I created a Budget description and budget value for each item.
I am trying to sum up all the values of the recyclerview. I have tried different methods over the night but failed to do. PLease help!!!
Adapter:
package com.example.personalwallet.Adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.personalwallet.Model.Budget;
import com.example.personalwallet.R;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
public class recyclerAdapter extends RecyclerView.Adapter<recyclerAdapter.MyViewHolder> {
private ArrayList<Budget> userlist;
private DatabaseReference databaseReference;
private String uId;
int sum=0;
public recyclerAdapter(ArrayList<Budget> userlist,String uId){
this.userlist=userlist;
this.uId = uId;
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(uId).child("Budget");
}
public class MyViewHolder extends RecyclerView.ViewHolder{
private TextView nameTxt,amountTXT;
CardView rootCardView;
ImageView deleteSupplierIV;
public MyViewHolder(final View view){
super(view);
nameTxt = view.findViewById(R.id.name);
amountTXT = view.findViewById(R.id.value);
rootCardView = itemView.findViewById(R.id.single_supplier_cardview_id);
deleteSupplierIV = itemView.findViewById(R.id.delete_supplier_IV);
}
}
#NonNull
#Override
public recyclerAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items,parent,false);
return new MyViewHolder(itemview);
}
#Override
public void onBindViewHolder(#NonNull recyclerAdapter.MyViewHolder holder, int position) {
Budget user = userlist.get(position);
String name,amount;
name = user.getBudgetDescription();
amount = user.getAmount();
holder.nameTxt.setText(name);
holder.amountTXT.setText(amount);
if (user.isVisibilityStatus()){
holder.deleteSupplierIV.setVisibility(View.GONE);
}
holder.rootCardView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
holder.deleteSupplierIV.setVisibility(View.VISIBLE);
user.setVisibilityStatus(false);
return true;
}
});
holder.deleteSupplierIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteSupplier(user.getBudgetDescription());
}
private void deleteSupplier(String supplierName) {
DatabaseReference productReference = databaseReference.child(supplierName);
productReference.removeValue();
userlist.remove(position);
notifyItemRemoved(position);
notifyDataSetChanged();
}
});
}
#Override
public int getItemCount() {
return userlist.size();
}
}
Activity Code:
package com.example.personalwallet.NavCategories;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.personalwallet.Adapter.recyclerAdapter;
import com.example.personalwallet.AddBudgetActivity;
import com.example.personalwallet.Model.Budget;
import com.example.personalwallet.Prevalent.Prevalent;
import com.example.personalwallet.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class Budgets extends AppCompatActivity{
private FloatingActionButton addNewBudgetFAB;
private ArrayList<Budget> userlist;
private RecyclerView recyclerView;
private String uId;
DatabaseReference databaseReference;
recyclerAdapter adapter;
TextView TotalBudgetTv;
public int total_budget =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_budgets);
userlist = new ArrayList<Budget>();
recyclerView = findViewById(R.id.suppliers_recyclerViewID);
TotalBudgetTv = findViewById(R.id.TotalBudgetTv);
uId = Prevalent.currentOnlineUser.getPhone();
adapter = new recyclerAdapter(userlist,uId);
setUserInfo();
setAdapter();
**for (int i=0; i<userlist.size(); i++){
total_budget = total_budget+Integer.parseInt(userlist.get(i).getAmount());
}**
TotalBudgetTv.setText("Total Budget: " + Integer.toString(total_budget));
addNewBudgetFAB = findViewById(R.id.addNewSuppliersFABID);
addNewBudgetFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Budgets.this, AddBudgetActivity.class);
startActivity(intent);
}
});
}
private void setAdapter() {
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
}
private void setUserInfo() {
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(uId).child("Budget");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
userlist.clear();
if (snapshot.exists()) {
for (DataSnapshot data : snapshot.getChildren()) {
Budget supplier = data.getValue(Budget.class);
userlist.add(supplier);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
this is my model class:
package com.example.personalwallet.Model;
public class Budget {
private String BudgetDescription;
private String amount;
public boolean isVisibilityStatus() {
return visibilityStatus;
}
public void setVisibilityStatus(boolean visibilityStatus) {
this.visibilityStatus = visibilityStatus;
}
private boolean visibilityStatus = true;
public Budget(){}
public Budget(String budgetDescription, String amount) {
BudgetDescription = budgetDescription;
this.amount = amount;
}
public String getBudgetDescription() {
return BudgetDescription;
}
public void setBudgetDescription(String budgetDescription) {
BudgetDescription = budgetDescription;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
Try to put your forloop calculation inside onDataChange because in oncreate method your userlist is empty. So when onDataChange called after that new value added to userlist and calculate your total there.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
userlist.clear();
if (snapshot.exists()) {
for (DataSnapshot data : snapshot.getChildren()) {
Budget supplier = data.getValue(Budget.class);
userlist.add(supplier);
adapter.notifyDataSetChanged();
}
for (int i=0; i<userlist.size(); i++)
{
total_budget = total_budget+Integer.parseInt(userlist.get(i).getAmount());
}
TotalBudgetTv.setText("Total Budget: " + Integer.toString(total_budget));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
In the adapter's constructor you will get the ArrayList which contains all data. Here, you can run a for loop. which will read each object one by one and add in sum.
public recyclerAdapter(ArrayList<Budget> userlist, String uId){
this.userlist=userlist;
this.uId = uId;
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(uId).child("Budget");
for(int i = 0; i<userlist.size(); i++){
Budget user = userlist.get(i);
sum = sum + user.getAmount();
}
}
I am trying to search for users via their username from Fire-base database, but when I type the username in the search filed it shows a blank list-view. Here's what I've done so far.
SearchActivity.java
package com.example.logindesign;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.logindesign.UserListAdapter;
import com.example.logindesign.users;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
/**
* Created by User on 5/28/2017.
*/
public class SearchActivity extends AppCompatActivity {
private static final String TAG = "SearchActivity";
private static final int ACTIVITY_NUM = 1;
private Context mContext = SearchActivity.this;
//widgets
private EditText mSearchParam;
private ListView mListView;
//vars
private List<users> mUserList;
UserListAdapter mAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mSearchParam = (EditText) findViewById(R.id.search);
mListView = (ListView) findViewById(R.id.listView);
Log.d(TAG, "onCreate: started.");
hideSoftKeyboard();
initTextListener();
}
private void initTextListener(){
Log.d(TAG, "initTextListener: initializing");
mUserList = new ArrayList<>();
mSearchParam.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String text = mSearchParam.getText().toString().toLowerCase(Locale.getDefault());
searchForMatch(text);
}
});
}
private void searchForMatch(String keyword){
Log.d(TAG, "searchForMatch: searching for a match: " + keyword);
mUserList.clear();
//update the users list view
if(keyword.length() ==0){
}else{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Users")
.orderByChild("Username").equalTo(keyword);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found user:" + Objects.requireNonNull(Objects.requireNonNull(singleSnapshot.getValue(users.class)).toString()));
mUserList.add(singleSnapshot.getValue(users.class));
//update the users list view
updateUsersList();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
private void updateUsersList(){
Log.d(TAG, "updateUsersList: updating users list");
mAdapter = new UserListAdapter(SearchActivity.this, R.layout.layout_user_listitem, mUserList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected user: " + mUserList.get(position).toString());
//navigate to profile activity
}
});
}
private void hideSoftKeyboard(){
if(getCurrentFocus() != null){
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
}
UserListAdapter.java
package com.example.logindesign;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import java.util.List;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by User on 9/17/2017.
*/
public class UserListAdapter extends ArrayAdapter<users> {
private static final String TAG = "UserListAdapter";
private LayoutInflater mInflater;
List<users> mUsers = null;
private int layoutResource;
private Context mContext;
public UserListAdapter(#NonNull Context context, #LayoutRes int resource, #NonNull List<users> objects) {
super(context, resource, objects);
mContext = context;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutResource = resource;
this.mUsers = objects;
}
private static class ViewHolder{
TextView username, email;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.username = convertView.findViewById(R.id.username);
holder.email = convertView.findViewById(R.id.email);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.username.setText(Objects.requireNonNull(getItem(position)).getUsername());
holder.email.setText(Objects.requireNonNull(getItem(position)).getEmail());
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Users")
.orderByChild("Username")
.equalTo(Objects.requireNonNull(getItem(position)).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot: dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found user: " +
Objects.requireNonNull(singleSnapshot.getValue(users.class)));
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return convertView;
}
}
The results are like this. If you look closely you'll see there's a card-view for the info to be displayed but somehow it's hidden:
U need to pass the value of the list here :
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("Users")
.orderByChild("Username").equalTo(keyword);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: found user:" + Objects.requireNonNull(Objects.requireNonNull(singleSnapshot.getValue(users.class)).toString()));
mUserList.add(singleSnapshot.getValue(users.class));
//update the users list view
updateUsersList(mUserList);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
private void updateUsersList(List<users> mUserList){
////
}
It's for MainActivity.class
reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
if (user.getUsername().equals(keyword)) {
mUserList.add(user);
//update the users list view
updateUsersList(mUserList);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
and your User class should look like this :
package com.example.spacing.Model;
public class User {
private String username;
private String phone;
private String id;
private String imageURL;
private String email;
public User(String username, String email ,String phone, String id, String imageURL) {
this.username = username;
this.email=email;
this.phone = phone;
this.id = id;
this.imageURL = imageURL;
}
public String getImageURL() {
return imageURL;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public User() {
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
I knew my question is similar with the other questioners but it was not solved my problem because I am still curious about how to declare the item which is the children of parent node. This is my stucture data on my Firebase:
I've tried to created the classes for my case:
DolanIemClass.java
private String name_tourism;
private String location_tourism;
private String info_tourism;
private String telepon;
private String url_photo;
private String url_photo_collage;
private double lat_location_tourism;
private double lng_location_tourism;
public DolanItemClass() {
//constructor untuk panggilan ke DataSnapshot.getValue
}
public DolanItemClass(String name_tourism, String location_tourism, String info_tourism, String telepon, String url_photo, String url_photo_collage, double lat_location_tourism, double lng_location_tourism) {
this.name_tourism = name_tourism;
this.location_tourism = location_tourism;
this.info_tourism = info_tourism;
this.telepon = telepon;
this.url_photo = url_photo;
this.url_photo_collage = url_photo_collage;
this.lat_location_tourism = lat_location_tourism;
this.lng_location_tourism = lng_location_tourism;
}
public String getUrl_photo_collage() {
return url_photo_collage;
}
public String getName_tourism() {
return name_tourism;
}
public void setName_tourism(String name_tourism) {
this.name_tourism = name_tourism;
}
public String getLocation_tourism() {
return location_tourism;
}
public void setLocation_tourism(String location_tourism) {
this.location_tourism = location_tourism;
}
public String getInfo_tourism() {
return info_tourism;
}
public void setInfo_tourism(String info_tourism) {
this.info_tourism = info_tourism;
}
public String getTelepon() {
return telepon;
}
public void setTelepon(String telepon) {
this.telepon = telepon;
}
public String getUrl_photo() {
return url_photo;
}
public void setUrl_photo(String url_photo) {
this.url_photo = url_photo;
}
public double getLat_location_tourism() {
return lat_location_tourism;
}
public void setLat_location_tourism(double lat_location_tourism) {
this.lat_location_tourism = lat_location_tourism;
}
public double getLng_location_tourism() {
return lng_location_tourism;
}
public void setLng_location_tourism(double lng_location_tourism) {
this.lng_location_tourism = lng_location_tourism;
}
}
DolanViewHolder.class
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
public class DolanImageViewHolder extends RecyclerView.ViewHolder {
private final ImageView imgDetailData;
public DolanImageViewHolder(#NonNull View itemView) {
super(itemView);
imgDetailData = itemView.findViewById(R.id.img_detail_item_data);
}
public void showImageArray(DolanItemClass dolanItemClass){
Glide.with(itemView.getContext()).load(dolanItemClass.getUrl_photo_collage()).into(imgDetailData);
}
}
And the activity class to show the list
package co.id.roningrum.firebasearrayimage;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class DetailTouristListAct extends AppCompatActivity {
private ImageView imgDetailData;
private TextView tvNamaDetail, tvAlamatDetail, tvDescDetail;
private RecyclerView rvImageDetailCollages;
private DatabaseReference databaseReference;
private ValueEventListener valueEventListener;
private FirebaseRecyclerAdapter<DolanItemClass, DolanImageViewHolder> firebaseRecyclerAdapter;
public static final String EXTRA_WISATA_KEY = "tourist_key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_tourist_list);
String touristKey = getIntent().getStringExtra(EXTRA_WISATA_KEY);
if(touristKey == null){
throw new IllegalArgumentException("Must pass Extra");
}
imgDetailData = findViewById(R.id.img_detail_data);
tvNamaDetail = findViewById(R.id.tv_name_detail);
tvAlamatDetail = findViewById(R.id.tv_info_tourism_detail);
tvDescDetail = findViewById(R.id.tv_address_detail);
rvImageDetailCollages = findViewById(R.id.rv_photo_collage);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Tourism").child(touristKey);
rvImageDetailCollages.setLayoutManager(new GridLayoutManager(this, 2));
LoadDetailData();
}
private void ShowCollage() {
Query query = databaseReference.child("url_photo_collage");
FirebaseRecyclerOptions<DolanItemClass> options = new FirebaseRecyclerOptions.Builder<DolanItemClass>()
.setQuery(query, DolanItemClass.class)
.build();
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<DolanItemClass, DolanImageViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull DolanImageViewHolder dolanImageViewHolder, int i, #NonNull DolanItemClass dolanItemClass) {
dolanImageViewHolder.showImageArray(dolanItemClass);
}
#NonNull
#Override
public DolanImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new DolanImageViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image_data, parent, false));
}
};
firebaseRecyclerAdapter.notifyDataSetChanged();
rvImageDetailCollages.setAdapter(firebaseRecyclerAdapter);
}
private void LoadDetailData() {
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
DolanItemClass dolanItemClass = dataSnapshot.getValue(DolanItemClass.class);
tvNamaDetail.setText(dolanItemClass.getName_tourism());
tvAlamatDetail.setText(dolanItemClass.getLocation_tourism());
tvDescDetail.setText(dolanItemClass.getInfo_tourism());
Glide.with(getApplicationContext()).load(dolanItemClass.getUrl_photo()).into(imgDetailData);
ShowCollage();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
databaseReference.addValueEventListener(eventListener);
valueEventListener = eventListener;
}
#Override
protected void onStart() {
super.onStart();
LoadDetailData();
if(firebaseRecyclerAdapter!=null){
firebaseRecyclerAdapter.startListening();
}
}
#Override
protected void onStop() {
super.onStop();
databaseReference.removeEventListener(valueEventListener);
}
}
I expected that I can show the array of url_photo_collage node but I don't have any idea for my item class.
The problem in your code is that your url_photo_collage field is declared in your DolanItemClass class of type String while in your database is an array. To solve this, change the type of your field from String to a List<String> and get it accordingly in your adapter.
I have a very serious problem. I am using a RecyclerView to populate data(a list of users) from Firebase into my application. Now the problem is that how to reference their respective userIds when a user clicks any of them so it can be used to set the title of the activity's action bar that will be opened. I tried using the getRef() method but it could not be resolved. Below is my code.
My StudentsList
package com.dreamlazerstudios.gtuconline;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import static android.content.ContentValues.TAG;
public class StudentsList extends AppCompatActivity {
DatabaseReference databaseReference;
ProgressDialog progressDialog;
List<Students> listData;
RecyclerView recyclerView;
StudentsList.MyAdapter adapter;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private FirebaseDatabase mFirebaseDatabase;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_students_list);
setTitle("List of Students");
recyclerView = findViewById(R.id.students_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
listData = new ArrayList<>();
adapter = new StudentsList.MyAdapter(listData);
adapter.setHasStableIds(true);
GetDataFirebase();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
final FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
void GetDataFirebase() {
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child("Students");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Students students = dataSnapshot.getValue(Students.class);
listData.add(students);
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
public class MyAdapter extends RecyclerView.Adapter<StudentsList.MyAdapter.ViewHolder> {
List<Students> list;
public MyAdapter(List<Students> List) {
this.list = List;
}
#Override
public void onBindViewHolder(final StudentsList.MyAdapter.ViewHolder holder, final int position) {
Students students = list.get(position);
String list_user_id = getRef(position).getKey();
holder.news_topic.setText(students.getName());
holder.news_body.setText(students.getProgramme());
if (students.getOnline() == true) {
holder.online.setVisibility(View.VISIBLE);
} else {
holder.online.setVisibility(View.INVISIBLE);
}
Picasso.with(holder.news_image.getContext()).load(students.getThumb_image()).placeholder(R.drawable.student_icon_17870).into(holder.news_image);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent chat_intent = new Intent(StudentsList.this, ChatActivity.class);
chat_intent.putExtra("user_id", list_user_id );
startActivity(chat_intent);
}
});
}
#NonNull
#Override
public StudentsList.MyAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.users_list_layout, parent, false);
return new StudentsList.MyAdapter.ViewHolder(view);
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView news_topic, news_body;
CircleImageView news_image;
ImageView online;
public ViewHolder(View itemView) {
super(itemView);
news_topic = itemView.findViewById(R.id.user_single_name);
news_body = itemView.findViewById(R.id.user_single_status);
news_image = itemView.findViewById(R.id.user_single_image);
online = itemView.findViewById(R.id.online_status_icon);
}
}
#Override
public int getItemCount() {
return list.size();
}
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
My model class
package com.dreamlazerstudios.gtuconline;
/**
* Created by Gabriel Hagan on 16/05/2018 at 23:10.
*/
public class Students {
String name;
String programme;
String thumb_image;
Boolean online;
public Boolean getOnline() {
return online;
}
public void setOnline(Boolean online) {
this.online = online;
}
public Students() {
}
public Students(String name, String programme, String thumb_image, Boolean online) {
this.name = name;
this.programme = programme;
this.thumb_image = thumb_image;
this.online = online;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProgramme() {
return programme;
}
public void setProgramme(String programme) {
this.programme = programme;
}
public String getThumb_image() {
return thumb_image;
}
public void setThumb_image(String thumb_image) {
this.thumb_image = thumb_image;
}
}
My ChatActivity
package com.dreamlazerstudios.gtuconline;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class ChatActivity extends AppCompatActivity {
private DatabaseReference rootRef;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private String userID;
private String mChatUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
rootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
final FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mChatUser = getIntent().getStringExtra("user_id");
rootRef.child("Users").child("Students").child(mChatUser).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String chat_user_name = dataSnapshot.child("name").getValue().toString();
setTitle(chat_user_name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
rootRef.child("Chat").child(userID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
My database snapshot
You can get the key from the DataSnapshot you are getting in onChildAdded. Instead of having a list of students in your adapter, you could keep the list of DataSnapshots. Then you could do something like this:
In StudentsList, change:
List<Students> listData;
To:
List<DataSnapshot> listData;
Also, change onChildAdded:
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
listData.add(dataSnapshot);
//Should probably move these since they don't need to get called for every item.
recyclerView.setAdapter(adapter);
progressDialog.dismiss();
}
Then in your adapter:
public class MyAdapter extends RecyclerView.Adapter<StudentsList.MyAdapter.ViewHolder> {
List<DataSnapshot> list;
public MyAdapter(List<DataSnapshot> List) {
this.list = List;
}
#Override
public void onBindViewHolder(final StudentsList.MyAdapter.ViewHolder holder, final int position) {
DataSnapshot studentSnapshot = list.get(position);
String list_user_id = studentSnapshot.getKey();
Students students = studentSnapshot.getValue(Students.class)
//The rest unchanged
Inside onBindViewHolder method you can get the key of the user that you are looking for using the following line of code:
String list_user_id = getItem(position);
getRef() is used to obtain a reference to the source location for the snapshot. So you can only use this method on a snapshot object. It returns a DatabaseReference and takes no argument. Below an example:
DatabaseReference ref = dataSnapshot.child("users").getRef();