Hello everyone I need to get user_fname from other table reference with uid
Below this my code
I'm use IndexedQuery and not clear from tutorial and sample code Firebase Ui
mRef = FirebaseDatabase.getInstance().getReference().child("mainboard");
mReference = FirebaseDatabase.getInstance().getReference().child("user");
mRecyclerView = view.findViewById(R.id.mainboard_alllist);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mLayoutManager = new LinearLayoutManager(getContext());
mOption = new FirebaseRecyclerOptions.Builder<Mainboard>().
setIndexedQuery(mRef , mReference ,Mainboard.class)
.setLifecycleOwner(this)
.build();
mAdapter = new FirebaseRecyclerAdapter<Mainboard, MainboardViewHolder>(mOption) {
#Override
public MainboardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.mainboard_list , parent , false);
return new MainboardViewHolder(view);
}
#Override
protected void onBindViewHolder(MainboardViewHolder holder, int postion, Mainboard mainboard) {
String mb_id = mainboard.mb_id;
mRef.child( mb_id + "/mb_auther").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String mb_author = dataSnapshot.getValue().toString();
mReference.child(mb_author + "/user_fname").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String user_fname = dataSnapshot.getValue().toString();
Log.e("user_fname" , dataSnapshot.getValue().toString());
holder.setAuthor(user_fname);
}
}
}
};
}
}
Straight method
1.First get the mb_auther value using addListenerForSingleValueEvent listener
2.Then using that mb_auther value get the user_fname
mRef.child("id/mb_auther").addListenerForSingleValueEvent(new ValueEventListener() { //Your case id is -KrHOUwrsBbXHvUaOTIu
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String mb_auther = dataSnapshot.getValue().toString();
mReference.child(mb_auther + "/user_fname").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String user_fname = dataSnapshot.getValue().toString()
Log.e("user_fname", user_fname);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Related
My app have some users stored in firebase realtime database, each user have have a node "showGigCount" which should update if someone clicks on that user.
The problem:
If User 1 click on the data of User 2 then the showGigCount for User 1 will be incremented by 1 and showGigCount of User 2 will be decremented by 1. As you can see in the code I can successfully update the value of showGigCount for User 1 but the value of User 2 is not changing. Any suggestions would be highly appreciated. Below is my code. Thank You all
DashboardActivity
fAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
dRef = FirebaseDatabase.getInstance().getReference("Users");
if(fAuth.getCurrentUser() != null){
UID = FirebaseAuth.getInstance().getCurrentUser().getUid();
}
dRef.child(UID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
remainingClicks = Integer.parseInt(String.valueOf(snapshot.child("clicksRemain").getValue()));
showGigCount = Integer.parseInt(String.valueOf(snapshot.child("showGigCount").getValue()));
String username = String.valueOf(snapshot.child("name").getValue());
clicks.setText(String.valueOf(remainingClicks));
userName.setText(username);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
recyclerView = findViewById(R.id.dashboardRCV);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
LoadData();
}
private void LoadData() {
// This will display the data of a user if his showGigCount is greater than 0.
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = db.child("Users");
Query queryByShowGigCount = usersRef.orderByChild("showGigCount").startAt(1);
options = new FirebaseRecyclerOptions.Builder<ModelClass>()
.setQuery(queryByShowGigCount, ModelClass.class)
.build();
adapter = new FirebaseRecyclerAdapter<ModelClass, MyViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull MyViewHolder holder, int position, #NonNull ModelClass model) {
holder.previewLink.setURL(model.getGig(), new URLEmbeddedView.OnLoadURLListener() {
#Override
public void onLoadURLCompleted(URLEmbeddedData data) {
holder.previewLink.title(data.getTitle());
holder.previewLink.description(data.getDescription());
holder.previewLink.host(data.getHost());
holder.previewLink.thumbnail(data.getThumbnailURL());
holder.previewLink.favor(data.getFavorURL());
}
});
String user_clicked = getRef(position).getKey();
if (user_clicked.equals(UID)){
holder.previewLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("if1 working", "it's showing the data");
Toast.makeText(DashboardActivity.this, "Opening your link is not allowed", Toast.LENGTH_LONG).show();
}
});
}else if (!user_clicked.equals(UID)){
holder.previewLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Online User", "Online user clicking");
if (remainingClicks >= 1) { // This code increment the showGigCount of User 1 by 1.
remainingClicks--;
showGigCount ++;
clicks.setText(String.valueOf(remainingClicks));
UserClicksCounts();
UserShowGigCounts();
// I wrote this code so that showGigCount of User 2 will be decreased by 1 but it's not working
dRef.child(String.valueOf(user_clicked)).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
showGigCount--;
UserGigCountDecrease();
Log.d("CLicked User", "showGigCount decreased");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
} else if (remainingClicks == 0){
zeroClicks.setVisibility(View.VISIBLE);
}
}
});
}
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_layout, parent, false);
return new MyViewHolder(view);
}
};
adapter.startListening();
recyclerView.setAdapter(adapter);
}
void UserClicksCounts(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Users").child(UID);
myRef.child("clicksRemain").setValue(remainingClicks);
}
// This will count how many times the gig will be shown to the user
void UserShowGigCounts(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Users").child(UID);
myRef.child("showGigCount").setValue(showGigCount);
void UserGigCountDecrease(){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Users").child(user_clicked);
myRef.child("showGigCount").setValue(showGigCount);
}
MyViewHolder Class
public MyViewHolder(#NonNull #NotNull View itemView) {
super(itemView);
previewLink = itemView.findViewById(R.id.uev);
geglink = (TextView) itemView.findViewById(R.id.rcvGigLink);
userName = (TextView) itemView.findViewById(R.id.rcvName);
userAbout = (TextView) itemView.findViewById(R.id.rcvAbout);
v = itemView;
}
To solve this I added these lines in the OnCLickListener
> user_clicked = getRef(position).getKey();
> assert user_clicked != null;
> dRef.child(user_clicked).child("showGigCount").setValue(model.getShowGigCount()-1);
It's now successfully decrementing the showGigCount of User 2.
I also removed the following lines of code
dRef.child(String.valueOf(user_clicked)).addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
showGigCount--;
UserGigCountDecrease();
Log.d("CLicked User", "showGigCount decreased");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
I am developing an app based on placement. I have used firebase realtime database for this. I am matching company name from the "Job Post" db and "Applied Candidate" db, so that only applied candidates detail for that particular company will be displayed. Everything is working fine but the issue is the recyclerview's data loads only when the button is clicked the second time.
public class AppliedCandidateActivity extends AppCompatActivity {
Toolbar toolbarAppliedcandidate;
RecyclerView rvAppliedCandidate;
List<appliedData> ls;
String compNameposted;
AppCandidateAdapter adapter;
DatabaseReference dbJobPost,dbAppliedCandidate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.applied_candidate);
toolbarAppliedcandidate = findViewById(R.id.toolbarAppliedcandidate);
rvAppliedCandidate = findViewById(R.id.rvAppliedCandidate);
setSupportActionBar(toolbarAppliedcandidate);
getSupportActionBar().setTitle("Applied Candidate");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
rvAppliedCandidate.setHasFixedSize(true);
rvAppliedCandidate.setLayoutManager(new LinearLayoutManager(this));
ls = new ArrayList<>();
adapter = new AppCandidateAdapter(getApplicationContext(),ls);
rvAppliedCandidate.setAdapter(adapter);
getCompany();
matchCompanyName();
}
void getCompany()
{
//To retrieve company name
dbJobPost = FirebaseDatabase.getInstance().getReference("Job Post").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
dbJobPost.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren())
{
PostJobData postJobData = ds.getValue(PostJobData.class);
compNameposted = postJobData.getCompName().toString();
//Toast.makeText(getApplicationContext(),postJobData.getCompName(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
void matchCompanyName()
{
//To retrieve data of applied candidate for particular company
dbAppliedCandidate = FirebaseDatabase.getInstance().getReference("Applied Candidate");
dbAppliedCandidate.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren())
{
for (DataSnapshot ds1 : ds.getChildren())
{
appliedData data = ds1.getValue(appliedData.class);
String compName = data.getCompName().toString();
//Toast.makeText(getApplicationContext(),compName,Toast.LENGTH_LONG).show();
if(compName.equals(compNameposted))
{
ls.add(data);
}
else if(ls.isEmpty()== true){
Toasty.info(AppliedCandidateActivity.this,"No One Applied Yet!!",Toast.LENGTH_LONG,true).show();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
public class AppCandidateAdapter extends RecyclerView.Adapter<AppCandidateAdapter.AppCandidateViewHolder>{
List<appliedData> appliedDataList;
Context context;
public AppCandidateAdapter(Context mcontext,List list){
this.context = mcontext;
this.appliedDataList = list;
}
#NonNull
#Override
public AppCandidateViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.applied_candidate_compside,parent,false);
return new AppCandidateViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AppCandidateViewHolder holder, int position) {
appliedData data = appliedDataList.get(position);
holder.tvCandidateName.setText(data.getName());
holder.tvCandidateAppliedPost.setText(data.getPosition());
holder.tvCandidateQual.setText(data.getQualification());
holder.tvCandidateSkills.setText(data.getSkills());
}
#Override
public int getItemCount() {
return appliedDataList.size();
}
class AppCandidateViewHolder extends RecyclerView.ViewHolder{
TextView tvCandidateName,tvCandidateAppliedPost,tvCandidateQual,tvCandidateSkills;
Button btnDeleteCandidate,btnSendMail;
public AppCandidateViewHolder(#NonNull View itemView) {
super(itemView);
tvCandidateName = itemView.findViewById(R.id.tvCandidateName);
tvCandidateAppliedPost = itemView.findViewById(R.id.tvCandidateAppliedPost);
tvCandidateQual = itemView.findViewById(R.id.tvCandidateQual);
tvCandidateSkills = itemView.findViewById(R.id.tvCandidateSkills);
btnDeleteCandidate = itemView.findViewById(R.id.btnDeleteCandidate);
btnSendMail = itemView.findViewById(R.id.btnSendMail);
}
}
}
}
Assuming your onDataChange does get called, successfully reads the PostJobData data from the snapshot, and adds it to ls, you're not telling Android that the list has changed. Only once you notify the adapter of the change, will it rerender the view.
dbJobPost = FirebaseDatabase.getInstance().getReference("Job Post").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
dbJobPost.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
PostJobData postJobData = ds.getValue(PostJobData.class);
compNameposted = postJobData.getCompName().toString();
}
adapter.notifyDataSetChanged(); // notify the adapter
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
I am trying to show random users from Firebase Realtime Database .I am currently able to show one random user from my Firebase Realtime database but what i want to do is show 6 random users on to my recyclerview at once .But i am unable to figure out how to add query for same without getting an error at runtime.
Mycode
public class UsersFragment extends Fragment {
private RecyclerView recyclerView;
private UserAdapter mUserAdapter;
private List<User> mUsers;
String TAG = "MyTag";
ValueEventListener mValueEventListener;
List<String> UserIdsList = new ArrayList<>();
public UsersFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_users, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mUsers = new ArrayList<>();
//readUser();
RandomUsers();
return view;
}
private void RandomUsers() {
//mUsers.add((User) UserIdsList);
mUserAdapter = new UserAdapter(getContext(), mUsers, false);
recyclerView.setAdapter(mUserAdapter);
mUserAdapter.notifyDataSetChanged();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference UserIdsRef = rootRef.child("UserIds");
ValueEventListener mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String userIDS = ds.getKey();
UserIdsList.add(userIDS);
}
int UserListSize = UserIdsList.size();
Log.d(TAG, String.valueOf(UserListSize));
Random random=new Random();
int random1=random.nextInt(UserListSize);
// int Rdm= UserIdsList.get(new Random().nextInt(UserListSize));
DatabaseReference UserRef = rootRef.child("Users").child(UserIdsList.get(random1));
Log.d(TAG,"UserRef "+ String.valueOf(UserRef));
//new Random().nextInt(UserListSize)
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
mUsers.add(user);
mUserAdapter.notifyDataSetChanged();
String name = dataSnapshot.child("First").getValue(String.class);
Log.d(TAG, "Name called "+name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.toException()); //Don't ignore errors!
}
};
UserRef.addListenerForSingleValueEvent(eventListener);
//UserRef.addValueEventListener(eventListener);
Query query2 = UserRef.limitToFirst(2);
query2.addListenerForSingleValueEvent(eventListener);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.getMessage()); //Don't ignore errors!
}
};
UserIdsRef.addListenerForSingleValueEvent(mValueEventListener);
//UserIdsRef.addValueEventListener(mValueEventListener);
}
}
UserAdapter.java
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private Context mContext;
private List<User> mUsers;
private List<String> UserIdsList;
private boolean ischat;
String theLastMessage;
public UserAdapter(Context mContext, List<User> mUsers,boolean ischat) {
this.mContext = mContext;
this.mUsers = mUsers;
this.ischat=ischat;
}
#NonNull
#Override
public UserAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(mContext).inflate(R.layout.user_item,parent,false);
return new UserAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.ViewHolder holder, int position) {
final User user=mUsers.get(position);
holder.username.setText(user.getFirst());
if (user.getImageURL().equals("default")){
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(mContext).load(user.getImageURL()).into(holder.profile_image);
}
if (ischat){
lastMessage(user.getId(), holder.last_msg);
} else {
holder.last_msg.setVisibility(View.GONE);
}
if (ischat){
if (user.getStatus().equals("online")){
holder.img_on.setVisibility(View.VISIBLE);
holder.img_off.setVisibility(View.GONE);
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.VISIBLE);
}
} else {
holder.img_on.setVisibility(View.GONE);
holder.img_off.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(mContext, MessageActivity.class);
intent.putExtra("UserName",user.getFirst());
intent.putExtra("userid", user.getId());
intent.putExtra("ImageURL",user.getImageURL());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mUsers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView username;
public ImageView profile_image;
private ImageView img_on;
private ImageView img_off;
private TextView last_msg;
public ViewHolder(#NonNull View itemView) {
super(itemView);
username=itemView.findViewById(R.id.username);
profile_image=itemView.findViewById(R.id.profile_image);
img_on = itemView.findViewById(R.id.img_on);
img_off = itemView.findViewById(R.id.img_off);
last_msg=itemView.findViewById(R.id.last_msg);
}
}
private void lastMessage(final String userid, final TextView last_msg){
theLastMessage = "default";
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Chat chat = snapshot.getValue(Chat.class);
if (firebaseUser != null && chat != null) {
if (chat.getReceiver().equals(firebaseUser.getUid()) && chat.getSender().equals(userid) ||
chat.getReceiver().equals(userid) && chat.getSender().equals(firebaseUser.getUid())) {
theLastMessage = chat.getMessage();
}
}
}
switch (theLastMessage){
case "default":
last_msg.setText("No Message");
break;
default:
last_msg.setText(theLastMessage);
break;
}
theLastMessage = "default";
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
Data Snapshot
DataSnapshot { key = KRhmaWXCctMHbU1Z6NAWRGGw2ag2, value = {EmailId=abc#gmail.com, First=shivam} }
You can try this:
DatabaseReference UserRef = rootRef.child("Users").orderByKey().startAt(UserIdsList.get(random1)).limitToFirst(6);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
mUsers.add(user);
mUserAdapter.notifyDataSetChanged();
String name = dataSnapshot.child("First").getValue(String.class);
Log.d(TAG, "Name called "+name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: " + databaseError.toException());
}
};
UserRef.addListenerForSingleValueEvent(eventListener);
I have been having some trouble updating my Friends list(mListView) view in real time in the application, it only seems to update when it is launched. I know its a matter of an update function but i do not know what to use.
(I'm rather new to firebase and android, and i'm still learning about them.)
Here is the code:
private ListView mListView;
private ArrayList<String> mFriends;
private List<User> mUserList;
private UserListAdapter mAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile_friends, container, false);
mSearchParam = (EditText) view.findViewById(R.id.searchFriends);
mListView = (ListView) view.findViewById(R.id.lvProfileFriends);
mPhotos = new ArrayList<>();
mUserList = new ArrayList<>();
mFriends = new ArrayList<>();
DisplayFriends();
return view;
}
private void DisplayFriends(){
getFriends();
}
private void updateUsersList(){
Log.d(TAG, "updateUsersList: updating users list");
mAdapter = new UserListAdapter(getActivity(), 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
Intent intent = new Intent(getActivity(), ViewProfileFragment.class);
intent.putExtra(getString(R.string.calling_activity), getString(R.string.fragment_profile));
intent.putExtra(getString(R.string.intent_user), mUserList.get(position));
startActivity(intent);
}
});
}
private void updateFriendsList(){
Log.d(TAG, "getPhotos: getting Friend(s)");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
for(int i = 0; i < mFriends.size(); i++){
final int count = i;
Query query = reference
.child(getString(R.string.dbname_users))
.orderByChild(getString(R.string.field_user_id))
.equalTo(mFriends.get(i));
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
mUserList.add(singleSnapshot.getValue(User.class));
}
if(count >= mFriends.size() - 1){
updateUsersList();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
private void getFriends(){
Log.d(TAG, "getFollowing: searching for FRIENDS **************************************");
mFriends.clear();
mUserList.clear();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_friends))
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot singleSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange: found friend----------------**: " + singleSnapshot.getValue(User.class).toString());
mFriends.add(singleSnapshot.child(getString(R.string.field_user_id)).getValue().toString());
Log.d(TAG, "onDataChange: Freinds user id: " + mFriends.toString() );
}
updateFriendsList();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Have a look at this:
DatabaseReference dref;
ListView listview;
ArrayList<String> list=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(ListView)findViewById(R.id.listview);
final ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,list);
listview.setAdapter(adapter);
dref=FirebaseDatabase.getInstance().getReference();
dref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
list.add(dataSnapshot.getValue(String.class));
adapter.notifyDataSetChanged();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
list.remove(dataSnapshot.getValue(String.class));
adapter.notifyDataSetChanged();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Whenever you receive a firebase update on friendList you can call adapter.notifyDataSetChanged() on the adapter that way adapter would know that an update has to be performed.
I would suggest you to use RecyclerView for this purpose as it is more flexible than a listview.
I am creating an app with Firebase in which user can share quotes. Data is inserted successfully and it looks like this in database after each value inserted.
please see this image for database values:
and I want to fetch all the data in an ArrayList. and onclick of refresh button the TextView should be updated to new value that will be randomly selected from ArrayList. I have tried something like this. but its not working. it showing nullpointerexception.
public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) {
this.localView = paramLayoutInflater.inflate(R.layout.fragmenthome, paramViewGroup, false);
story = (TextView) localView.findViewById(R.id.story_text);
rl = (RelativeLayout) localView.findViewById(R.id.rlLayout);
linearLayout = (LinearLayout) localView.findViewById(R.id.bottom_bar);
imgRefresh = (ImageView) localView.findViewById(R.id.refreshStory);
databaseReference = FirebaseDatabase.getInstance().getReference().child("stories");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
storiesary = new ArrayList<String>();
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
storiesary.add(childSnapshot.getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
imgRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setStory();
}
});
return localView;
}
public void setStory()
{
int arraysize = storiesary.size();
final int arrayposition1 = (new Random()).nextInt(arraysize);
story.setText(storiesary.get(arrayposition1));
}
Try this
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
storiesary = new ArrayList<String>();
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
HashMap map =(HashMap) childSnapshot.getValue();
if(map!=null) {
storiesary.add(map.get("storytext"));
}
//or
String name = (String) childSnapshot.child("storytext").getValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG,"Error");
}
});