Android Studio displaying FirebaseListAdapter change codes - android

i have a FirebaseListAdapter which retrieves all the uid from the user but i want it to retrieve the names instead.
i have two child. one is to store all the uid of the connected users for a chat, and the other contains their information such as names. how do i convert the retrieved values (uid) into names and display it as shown below.
i have attached a snippet of how my app looks like currently and i want it to show names instead of uid.
FirebaseListAdapter<String> firebaseListAdapter = new FirebaseListAdapter<String>(getActivity(), String.class, R.layout.fragment_chatfprow, mDatabase) {
#Override
protected void populateView(View v, String model, int position) {
TextView text = v.findViewById(R.id.text1);
text.setText(model);
}
};
i think there is something to do with these lines of code but i cant figure out how.
This is how my Firebase ListView looks like

You need a model class for Firebase UI Database with an empty constructor for example:
public class Users {
private String mName;
private String mMessage;
public Users() {} // Required for Firebase
public Users(String name, String message) {
mName = name;
mMessage = message;
}
public String getName() { return mName; }
public void setName(String name) { mName = name; }
public String getMessage() { return mMessage; }
public void setMessage(String message) { mMessage = message; }
}
Then in Adapter creation you can do like this:
FirebaseListAdapter<Users> firebaseListAdapter = new FirebaseListAdapter<Users>(getActivity(), Users.class, R.layout.fragment_chatfprow, mDatabase) {
#Override
protected void populateView(View v, String model, int position) {
TextView text = v.findViewById(R.id.text1);
text.setText(model.getName());
}
};
You can take a look here from more informations: https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md

Related

Android/Firebase realtime-database how get only last message?

I'm using the firebase Database at the Android Studio. Code java. I use realtime database.
I'm doing a Chat app. I want to show users the last message in their inbox.
I have this database:
message: {
User uıd: {
Uid of the person he is talking to: {
random key: {
-date
-from
-message
-time
-type
}
}
}
I have ref to database als:
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ChatsRef=FirebaseDatabase.getInstance().getReference().child("message").child(currentUserID);
I'm using this to get :
public void messageegetir(){
FirebaseRecyclerOptions<Messages> options =
new FirebaseRecyclerOptions.Builder<Messages>()
.setQuery(ChatsRef,Messages.class)
.build();
FirebaseRecyclerAdapter<Messages, ChatsViewHolder> adapter =
new FirebaseRecyclerAdapter<Messages, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, final int position, #NonNull final Messages model) {
final String usersIDs = getRef(position).getKey();
final String[] retImage = {"default_image"};
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.message_list_model,viewGroup,false);
return new ChatsViewHolder(view);
}
};
chatlist.setAdapter(adapter);
adapter.startListening();
updateUserStatus("online");
}
my publıc statıc class :
public static class ChatsViewHolder extends RecyclerView.ViewHolder{
CircleImageView profileImage ;
ImageView onlinestatus;
TextView lastmessage , userName ;
public ChatsViewHolder(#NonNull View itemView) {
super(itemView);
profileImage =itemView.findViewById(R.id.messageprofileimageee);
userName =itemView.findViewById(R.id.messagenameee);
lastmessage =itemView.findViewById(R.id.messageinfooo);
onlinestatus =itemView.findViewById(R.id.onlinestatus);
}
}
Messages class :
public class Messages {
public String data, time, type, message, from ;
public Messages(){
}
public Messages(String data, String time, String type, String message, String from) {
this.data = data;
this.time = time;
this.type = type;
this.message = message;
this.from = from;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
}
enter image description here
How can I get those data and write them in a textview?
i suggest that you modify your database structure , denormalize it like it is recommended by firebase docs. see the link https://firebase.google.com/docs/database/android/structure-data#best_practices_for_data_structure
And you will understand
I did a chat app and the way I did it is that I have two main roots and one is dedicated to getting the last sent message and it updated every time a new message is received and the other root is dedicated to storing a list of all messages between two users so I suggest doing something similar.

Update a RecyclerView from another class

I will try to be brief:
I have three classes that have to interact in this:
The server, which receives the message (in a thread).
The contact, which stores messages in its class (in each object).
The chat activity belonging to each user, which has to show the
messages of the corresponding object, the idea is that it is a RecyclerView.(an activity)
The server receives a message, this message would be added to the chat of the specific contact and then the RecyclerView must be updated.
This is the basic Contact class code:
public class Contact implements Serializable {
private String name;
private String ip;
//Here would be a variable that contains the chat strings
public Contact (String name, String ip){
this.name = name;
this.ip = ip;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
And then there is the activity of the chat that is launched when selecting a specific user and it contains a RecyclerView where I want the messages to be.
My problem is that, how to make the messages that are stored in the
variable of a specific object appear in the list.
From already thank you very much.
you can use data class instead of serialization
public class Data {
private String text;
private String uid;
private String tnviews;
private String numberlikes;
public Data(String text,String tnviews,String numberlikes,String uid) {
this.text = text;
this.tnviews = tnviews;
this.numberlikes = numberlikes;
this.uid = uid;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
/////////// VIEWS
public String getViews() {
return tnviews;
}
public void setViews(String tnviews) {
this.tnviews = tnviews;
}
//////// likes
public String getLikes() {
return numberlikes;
}
public void setLikes(String numberlikes) {
this.numberlikes = numberlikes;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
you can Update RecyclerView Adapter Data
mAdapter.notifyDataSetChanged();
Reference link

Android: reading a value from a child with FirebaseUI

I am using FirebaseUI to get some values from my real-time database to Firebase RecyclerView. So.. my data looks like that:
users:
userid:
info:
Name:Muhammad
I don't know how to get the value of Name which means what exactly should I do in the Users class? Here is my code (I think that the problem is in class user, I just don't know how to access child info)
public class User {
private String name;
private String email;
private String state;
private String image;
private String thumbnail;
public User(String name, String state, String image) {
this.name = name;
this.state = state;
this.image = image;
}
public User() {
}
public String getName() {
return name;
}
public String getState() {
return state;
}
public String getImage() {
return image;
}
}
my Main Activity
myDB refer to and on start method (updated after SUPERCILEX comment )
mDb = FirebaseDatabase.getInstance().getReference().child(App_Constants.USERS_COLUMN);
#Override
protected void onStart() {
super.onStart();
Query query = mDb;
FirebaseRecyclerOptions<User> options = new FirebaseRecyclerOptions.Builder<User>()
.setQuery(query, new SnapshotParser<User>() {
#NonNull
#Override
public User parseSnapshot(#NonNull DataSnapshot snapshot) {
String Name = snapshot.child(App_Constants.INFO_COLUMN).child(App_Constants.NAME_COLUMN).getValue().toString();
String State = snapshot.child(App_Constants.INFO_COLUMN).child(App_Constants.STATE_COLUMN).getValue().toString();
String Image = snapshot.child(App_Constants.INFO_COLUMN).child(App_Constants.IMAGE_COLUMN).getValue().toString();
User user = new User(Name,State,Image);
return user;
}
}).build();
FirebaseRecyclerAdapter<User,Users_ViewHolder> adapter = new FirebaseRecyclerAdapter<User, Users_ViewHolder>(options) {
#NonNull
#Override
public Users_ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_user,parent,false);
return new Users_ViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull Users_ViewHolder holder, int position, #NonNull User model) {
holder.Set_Name(model.getName());
holder.Set_Image(model.getImage());
holder.Set_State(model.getState());
}
};
mUsers.setAdapter(adapter);
}
my ViewHolder
public class Users_ViewHolder extends RecyclerView.ViewHolder{
View mView;
public Users_ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void Set_Name(String Name)
{
TextView mName = mView.findViewById(R.id.tv_single_user_name);
mName.setText(Name);
}
public void Set_Image(String url)
{
CircleImageView mImage = mView.findViewById(R.id.iv_single_user);
Picasso.get().load(url).placeholder(R.drawable.profile).into(mImage);
}
public void Set_State(String State)
{
TextView mState = mView.findViewById(R.id.tv_single_user_state);
mState.setText(State);
}
}
thanks
I believe it'll come in as a Map<String, Object> on the field info. However, you can always use a custom SnapshotParser to build your model to your liking: https://github.com/firebase/FirebaseUI-Android/blob/master/database/README.md#using-the-firebaserecycleradapter.
Some Advices :would you mind changing the set methods names?
from Set_State to setState,I too had similar problems please respect Java naming conventions
Also add the set methods in your custom model
Second:
FirebaseRecyclerOptions<User> options =
new FirebaseRecyclerOptions.Builder<User>()
.setQuery(query, User.class)
.build();
Start Listening:
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
stopListening() call removes the event listener and all data in the adapter
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
Here you have a very good explained example

unable to retrieve data from one app to another app from firebase single Database

I have 2 applications(different package names) which use one Firebase database. One app has to write access to the database and another have read access to the database.in my second application, i use recyclerview to retrieve data which is stored by 1st App.
for this I use below code:
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:567....259c8f58311") // Required for Analytics.
.setApiKey("AIzaSyA9BRxl......hE03y5qD-c") // Required for Auth.
.setDatabaseUrl("https://mycity-3a561.firebaseio.com/") // Required for RTDB.
.build();
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
// Get the database for the other app.
FirebaseDatabase secondaryDatabase = FirebaseDatabase.getInstance(app);
DatabaseReference data = secondaryDatabase.getInstance().getReference();
data.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
WaterClass waterClass = dSnapshot.getValue(WaterClass.class);
Log.d("Show", waterClass.getName() == null ? "" : waterClass.getName());
list.add(waterClass);
}
adapter = new WaterAdapter(ShowWaterDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
}
Adapter class
private class WaterAdapter extends RecyclerView.Adapter<WaterAdapter.ViewHolder> {
ShowWaterDetails showDetail;
List<WaterClass> listData;
public WaterAdapter(ShowWaterDetails showWaterDetails, List<WaterClass> list) {
this.showDetail = showWaterDetails;
this.listData = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.show_items, parent, false);
WaterAdapter.ViewHolder viewHolder = new WaterAdapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(WaterAdapter.ViewHolder holder, int position) {
WaterClass AllDetails = listData.get(position);
holder.NameTextView.setText(AllDetails.getName());
holder.DetailTextView.setText(AllDetails.getDetail());
holder.DateTextView.setText(AllDetails.getDate());
holder.LocationTextView.setText(AllDetails.getLocation());
holder.TypeTextView.setText(AllDetails.getType());
Picasso.with(showDetail).load(AllDetails.getImgurl()).resize(120, 60).into(holder.ImageTextView);
}
#Override
public int getItemCount() {
return listData.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView NameTextView;
public TextView DetailTextView;
public TextView DateTextView;
public TextView LocationTextView;
public TextView TypeTextView;
public ImageView ImageTextView;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = itemView.findViewById(R.id.ShowNameTextView);
DetailTextView = itemView.findViewById(R.id.ShowDetailTextView);
DateTextView = itemView.findViewById(R.id.ShowDateTextView);
LocationTextView = itemView.findViewById(R.id.ShowLocationTextView);
TypeTextView = itemView.findViewById(R.id.ShowTypeTextView);
ImageTextView = itemView.findViewById(R.id.ShowImageView);
}
}
}
}
POJO Class
class WaterClass {
private String id;
private String email;
private String name;
private String type;
private String detail;
private String location;
private String date;
private String imgurl;
public WaterClass(){
}
public WaterClass(String id, String currentUserString, String imageUrl, String nameString, String typeString, String detailString, String locationString, String dateString) {
this.id = id;
this.email = currentUserString;
this.name =nameString;
this.type = typeString;
this.detail = detailString;
this.location = locationString;
this.date = dateString;
this.imgurl = imageUrl;
}
public String getImgurl() {
return imgurl;
}
public void setImgurl(String imgurl) {
this.imgurl = imgurl;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
:
there is no error but my recycler not showing anything
go to onStart() and start listening
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
and in your onStop
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
The FirebaseRecyclerAdapter uses a snapshot listener to monitor changes to the Firestore query. To begin listening for data, call the startListening() method. You may want to call this in your onStart() method. Make sure you have finished any authentication necessary to read the data before calling startListening() or your query will fail.
Be sure that the names of constant in the POJO match exatly the names
of your database structure in your firebase console !!
ps: do not post your api-keys or app-ids in your questions, keep them secret, and consider using firebaserecycleradapter if you are using firebase-database , it will be more easy to setup and to show values.
Your POJO is ok !
Found Solution!!
just change this part of a code
FirebaseApp.initializeApp(this /* Context */, options, "MyCity");
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("MyCity");
TO
FirebaseApp.initializeApp(this);
// Retrieve my other app.
FirebaseApp app = FirebaseApp.getInstance("[DEFAULT]");

How to autocomplete text in a textview with firebase database in an android app

I want something like below image. Image is of autocomplete search from firebase website itself.
I've seen many post about this, but those posts does not seem to work with firebase above 3.0.
I want to search in an autcomplete textview either with entering name or number. Here's an entry from my database
In short, it should suggest entries from my firebase database as I start typing.
One solution for achieving this would be loading your data from the realtime database into an ArrayList before you start searching.
So to do this first you'll need to check when the Firebase Listener
is done retrieving your data from the database. Firebase Listeners are not executed in sequence and the ValueListener is always executed last. So you can do something like retrieve your data through a ChildListener and then execute to ValueListener to make sure the data is completely retrieved rootRef.addListenerForSingleValueEvent()
Later when your data is retrieved and stored in a arraylist you can follow this to add the search functionality
Hope it helps!
First of all add the required dependencies of firebase and glide or other dependency for image view in build.gradle .
Create a reference for the tree as follows
mUserDatabase = FirebaseDatabase.getInstance().getReference("YourTreeRootNameHere");
Pass the string in the text field with a onTextChanged method to the following function firebaseUserSearch. Make necessary changes in the following function according to your code.
private void firebaseUserSearch(String searchText) {
Query firebaseSearchQuery = mUserDatabase.orderByChild("sName").startAt(searchText).endAt(searchText + "\uf8ff");
FirebaseRecyclerAdapter<Users, SearchActivity.UsersViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Users, SearchActivity.UsersViewHolder>(
Users.class,
R.layout.list_layout,
SearchActivity.UsersViewHolder.class,
firebaseSearchQuery
) {
#Override
protected void populateViewHolder(SearchActivity.UsersViewHolder viewHolder, final Users model, final int position) {
viewHolder.setDetails(getApplicationContext(), model.getName(), model.getPlace(), model.getImage());
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
}
// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
View mView;
public UsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setDetails(Context ctx, String userName, String userStatus, String userImage){
TextView user_name = (TextView) mView.findViewById(R.id.name_text);
TextView user_status = (TextView) mView.findViewById(R.id.status_text);
ImageView user_image = (ImageView) mView.findViewById(R.id.profile_image);
user_name.setText(userName);
user_status.setText(userStatus);
Glide.with(ctx).load(userImage).into(user_image);
}
}
Create your layout for recyclerView and define the data model class. For example this function uses a Users.class that is shown below.
public class Users {
public String name, image, place;
public Users(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPlace() {
return place;
}
public void setPlace(String status) {
this.place = status;
}
public Users(String name, String image, String place) {
this.name = name;
this.image = image;
this.place = place;
}
}

Categories

Resources