Why I'm getting duplicated data from firebase database? - android

public class Post {
private String title;
private String massage;
public Post() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMassage() {
return massage;
}
public void setMassage(String massage) {
this.massage = massage;
}
}
public class Posts extends AppCompatActivity {
private DatabaseReference databaseReference, barRoomsCoordinates;
private FirebaseDatabase firebaseDatabase;
private List<Post> postList;
private List<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
postList = new ArrayList<>();
list = new ArrayList<>();
showAllMyPosts();
}
private void getPosts(List<String> posts) {
for (int i = 0; i < posts.size(); i++) {
databaseReference = firebaseDatabase.getReference().child("Posts").child(posts.get(i));
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Post posts = dataSnapshot.getValue(Post.class);
Post post = new Post();
post.setTitle(posts.getTitle());
post.setMassage(posts.getMassage());
postList.add(post);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
private void showAllMyPosts() {
FirebaseApp.initializeApp(Posts.this);
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
barRoomsCoordinates = firebaseDatabase.getReference().child("Posts");
barRoomsCoordinates.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext()) {
list.add(((DataSnapshot) iterator.next()).getKey());
}
getPosts(list);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
handler.post(runnable);
}
}
This is my database structure
Posts
Post1
message1:
"abc + something"
title1:
"abc"
Post2
message2:
"def + something"
title2:
"def"
Post3
message3:
"ghi + something"
title3:
"ghi"
I'm getting duplicated array and can't understand why
please help me.
I also tried delete one reference and make a call but in this way I can't access the children of the JSON.

This is happening because of your for loop. You are creating a new databaseReference every time you loop. Take the databaseReference out of your loop and it will solve your problem or try to change the logic of getting the data from your Firebase database.
Hope it helps.

public class Posts extends AppCompatActivity {
private DatabaseReference databaseReference, barRoomsCoordinates;
private FirebaseDatabase firebaseDatabase;
private List<Post> postList;
private List<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
postList = new ArrayList<>();
list = new ArrayList<>();
getPosts();
}
private void getPosts() {
databaseReference = firebaseDatabase.getReference().child("Posts");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext()) {
Post post = new Post();
post.setTitle((String) ((DataSnapshot)iterator.next()).getValue());
post.setMassage((String) ((DataSnapshot)iterator.next()).getValue());
postList.add(post);
}
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Hello all,
I solved my problem with one reference to the database instead of two calls as i did before and with addChildEventListener.
Thanks

Related

How do I store a data into the firebase database without updating it? and also retrieving the data

I am currently working on a project that might be useful in a store for the ordering of foods. The device can already store some data and retrieve but there are problems that I have been dealing with.
Problem 1#: First off is that every time I store a data it usually looks like this:
For some reason I tried to use child "02" because it displays in the recycler view if I do something like "Ordering" as a child it does not seem to be showing in the display. How do I add more data to it like example in the child 02 I can still add like milkshakes or candy bars? This is the code I have done for storing.
public class Detailsoforder extends AppCompatActivity {
private static final String TAG = "AddToDatabase";
private TextView titles;
private TextView increase;
private int count = 0;
//add Firebase
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailsoforder);
titles = findViewById(R.id.Order);
increase = findViewById(R.id.Increase);
String title = getIntent().getStringExtra("title");
titles.setText(title);
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
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");
}
}
};
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Object value = dataSnapshot.getValue();
Log.d(TAG,"Value is"+value);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void onIncreaseClick(View view) {
count++;
increase.setText(String.valueOf(count));
}
public void onOrderNow(View view) {
String value = increase.getText().toString();
if (value.equals("1")) {
Toast.makeText(Detailsoforder.this,"The order must be above 1", Toast.LENGTH_LONG).show();
}
else {
Log.d(TAG, "onClick: Attempting to add object to database.");
String newFood = titles.getText().toString();
if (!newFood.equals("")) {
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
myRef.child(userID).child("02").child("food").setValue(newFood);
myRef.child(userID).child("02").child("order").setValue(value);
Toast.makeText(Detailsoforder.this,"Adding " + newFood + " to database...", Toast.LENGTH_LONG).show();
//reset the text
titles.setText("");
Intent intent = new Intent(Detailsoforder.this, Placeorder.class);
startActivity(intent);
}
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
How do I store many data and not needing for updating it?
Problem 2#: Retrieving of the data. The problem is that I can only seem to get only 1 data. I wanted to fix the store part first so that I could check if I could get the many information. This is my code for retrieving of the data.
public class Vieworders extends AppCompatActivity {
private RecyclerView mRecyclerView1;
private ViewHolder1 mAdapter1;
private DatabaseReference mDatabaseReference1;
private List<Model1> mModel1;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vieworders);
mRecyclerView1= findViewById(R.id.recyclerview1);
mRecyclerView1.setHasFixedSize(true);
mRecyclerView1.setLayoutManager(new LinearLayoutManager(this));
mModel1 = new ArrayList<>();
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
mAdapter1=new ViewHolder1(Vieworders.this, mModel1);
mRecyclerView1.setAdapter(mAdapter1);
mDatabaseReference1= FirebaseDatabase.getInstance().getReference(userID);
mDatabaseReference1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
Model1 model1=postSnapshot.getValue(Model1.class);
mModel1.add(model1);
}
mAdapter1.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(Vieworders.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
Can someone help me, please? I really need this to be done.
I think you are able to send data to fire and able to store these datas.
Now ,this is my snipshots of fetching data from Firebase .You can take help from this code.
private RecyclerView recyclerView;
private List<RoomRentData> firebaselist;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private DualProgressView progressView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_rent_activity);
firebaselist=new ArrayList<>();
recyclerView=findViewById(R.id.rent_item);
progressView=findViewById(R.id.progressbar);
progressView.setVisibility(View.VISIBLE);
recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(),1));
recyclerView.setItemAnimator( new DefaultItemAnimator());
recyclerView.hasFixedSize();
final Calendar today = Calendar.getInstance();
String year=Integer.toString(today.get(Calendar.YEAR));
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("room_rent").child(year);
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
progressView.setVisibility(View.GONE);
System.out.println("1");
RoomRentData user = dataSnapshot.getValue(RoomRentData.class);
if (user == null) {
System.out.println("2");
Toast.makeText(ShowRentActivity.this,"No data found",Toast.LENGTH_LONG).show();
return;
}else {
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
System.out.println("datasnapshot 1"+dataSnapshot1);
System.out.println("3");
RoomRentData userdetails = dataSnapshot1.getValue(RoomRentData.class);
System.out.println("userdetails 1"+userdetails);
RoomRentData listdata = new RoomRentData();
String month=userdetails.getMonth();
String year=userdetails.getYear();
String cuRead=userdetails.getCurrentRead();
String prevRead=userdetails.getPrevUnit();
String totalRent=userdetails.getTotalRoomRent();
String perPersonCost=userdetails.getPerpersonCost();
String totalPeron=userdetails.getTotalPerson();
String paidOn=userdetails.getCurrentTimeAndDate();
String description=userdetails.getDescription();
System.out.println("description 1"+description);
System.out.println("month"+month);
listdata.setMonth(month);
listdata.setYear(year);
listdata.setCurrentRead(cuRead);
listdata.setPrevUnit(prevRead);
listdata.setTotalRoomRent(totalRent);
listdata.setPerpersonCost(perPersonCost);
listdata.setTotalPerson(totalPeron);
listdata.setCurrentTimeAndDate(paidOn);
listdata.setDescription(description);
firebaselist.add(listdata);
}
rentAdapter firebaseListAdapter=new rentAdapter(getApplicationContext(),firebaselist);
recyclerView.setAdapter(firebaseListAdapter);
}
}
#Override
public void onCancelled(DatabaseError error) {
progressView.setVisibility(View.GONE);
System.out.println(error);
System.out.println("error");
}
});
}
}
I have create a Model Class named RoomRentData.class.I have added this data to the RecyclerView using this model.
And This is my Model Class Code.
public class RoomRentData {
private String month;
private String year;
private String roomRent;
private String perUnitCost;
private String PrevUnit;
private String CurrentRead;
private String totalUnitCostt;
private String totalRoomRent;
private String totalPerson;
private String perpersonCost;
private String description;
private String currentTimeAndDate;
public String getCurrentRead() {
return CurrentRead;
}
public String getCurrentTimeAndDate() {
return currentTimeAndDate;
}
public String getDescription() {
return description;
}
public String getMonth() {
return month;
}
public String getPerpersonCost() {
return perpersonCost;
}
public String getPerUnitCost() {
return perUnitCost;
}
public String getPrevUnit() {
return PrevUnit;
}
public String getRoomRent() {
return roomRent;
}
public String getTotalPerson() {
return totalPerson;
}
public String getTotalRoomRent() {
return totalRoomRent;
}
public String getTotalUnitCostt() {
return totalUnitCostt;
}
public String getYear() {
return year;
}
public void setCurrentRead(String currentRead) {
CurrentRead = currentRead;
}
public void setCurrentTimeAndDate(String currentTimeAndDate) {
this.currentTimeAndDate = currentTimeAndDate;
}
public void setDescription(String description) {
this.description = description;
}
public void setMonth(String month) {
this.month = month;
}
public void setPerpersonCost(String perpersonCost) {
this.perpersonCost = perpersonCost;
}
public void setPerUnitCost(String perUnitCost) {
this.perUnitCost = perUnitCost;
}
public void setPrevUnit(String prevUnit) {
PrevUnit = prevUnit;
}
public void setRoomRent(String roomRent) {
this.roomRent = roomRent;
}
public void setTotalPerson(String totalPerson) {
this.totalPerson = totalPerson;
}
public void setTotalRoomRent(String totalRoomRent) {
this.totalRoomRent = totalRoomRent;
}
public void setTotalUnitCostt(String totalUnitCostt) {
this.totalUnitCostt = totalUnitCostt;
}
public void setYear(String year) {
this.year = year;
}
}

Recyclerview keeps re-populating data from Firebase DB when new child is created

I am currently working on a chat application and have come across an issue. My Chat Fragment contains my Recyclerview which populates data from Firebase DB. I am able to obtain the data, but I am running into an issue. When I open my Chat Activity and send a message, a new push id is created with the information stored in the child. The data obtained by my recyclerview is it gets the last push id and retrieves the last message that was sent. The problem is, when I go back into my fragment, the recyclerview re-populates and adds the new push id last message that was created, and creates another item instead of just refreshing the original item.
So essentially, I will load my app, go into the Chat Fragment, my recyclerview will display the other user and the last message that was sent, no problem, then I will click on that item, open the chat activity, send a message then go back. Now when I am back into the chat fragment I will have two or three or however many messages that were sent displaying in the recyclerview. Not sure on how to fix this, my code is below:
DATABASE STRUCTURE
Chat Fragment
public class Fragment_MatchChats extends Fragment {
private RecyclerView mRecyclerView, mRecyclerViewChat;
private RecyclerView.Adapter mMatchesAdapter, mChatAdapter;
private String currentUserID;
private DatabaseReference mDatabaseChat;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_match_chat, container, false);
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabaseChat = FirebaseDatabase.getInstance().getReference().child("Chat");
LinearLayoutManager layoutManagerChat = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
mRecyclerViewChat = (RecyclerView) v.findViewById(R.id.recyclerViewChat);
mRecyclerViewChat.setHasFixedSize(true);
mRecyclerViewChat.setLayoutManager(layoutManagerChat);
mChatAdapter = new RecyclerViewChatAdapter(getDataSetChat(), getContext());
getUserMatchId();
return v;
}
//this method will get the user ID in the database that you matched with. It will run through the matches child and get all the user IDs
private void getUserMatchId() {
DatabaseReference matchDB = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID).child("swipes").child("matches");
matchDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
for(DataSnapshot match : dataSnapshot.getChildren()){
CheckChatID(match.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void CheckChatID(final String chat) {
DatabaseReference ChatDB = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID).child("swipes").child("matches")
.child(chat).child("ChatID");
ChatDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String ChatID = dataSnapshot.getValue().toString();
ChatIDExist(ChatID, chat);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void ChatIDExist(final String chatID, final String oppUserID) {
final DatabaseReference ChatDB = mDatabaseChat.child(chatID);
final Query lastQuery = ChatDB.orderByKey().limitToLast(1);
ChatDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
lastQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child: dataSnapshot.getChildren()){
String key = child.child("text").getValue().toString();
FetchChatInfo(oppUserID,key);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void FetchChatInfo(String key, final String chatID) {
DatabaseReference userDB = FirebaseDatabase.getInstance().getReference().child("Users").child(key);
userDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String matched_userID = dataSnapshot.getKey();
String matches_userName = "";
String matches_userProPic = "";
String match_CHATID = chatID;
if(dataSnapshot.child("name").getValue() != null){
matches_userName = dataSnapshot.child("name").getValue().toString();
}
if(dataSnapshot.child("profilePicURL").getValue() != null){
matches_userProPic = dataSnapshot.child("profilePicURL").getValue().toString();
}
RecyclerViewChatReference chat_obj = new RecyclerViewChatReference(matched_userID, matches_userName, matches_userProPic, match_CHATID);
resultsChats.add(chat_obj);
mRecyclerViewChat.setAdapter(mChatAdapter);
mChatAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private ArrayList<RecyclerViewChatReference> resultsChats = new ArrayList<RecyclerViewChatReference>();
private List<RecyclerViewChatReference> getDataSetChat() {
return resultsChats;
}
Chat Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
matchId = getIntent().getExtras().getString("matchID");
currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserID)
.child("swipes").child("matches").child(matchId).child("ChatID");
mDatabaseChat = FirebaseDatabase.getInstance().getReference().child("Chat");
getChatId();
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setNestedScrollingEnabled(false);
mRecyclerView.setHasFixedSize(false);
mChatLayoutManager = new LinearLayoutManager(ChatActivity.this);
mRecyclerView.setLayoutManager(mChatLayoutManager);
mChatAdapter = new ChatAdapter(getDataSetChat(), ChatActivity.this);
mRecyclerView.setAdapter(mChatAdapter);
mSendEditText = findViewById(R.id.message);
mSendButton = findViewById(R.id.send);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
}
private void sendMessage() {
String sendMessageText = mSendEditText.getText().toString();
if(!sendMessageText.isEmpty()){
DatabaseReference newMessageDb = mDatabaseChat.push();
Map newMessage = new HashMap();
newMessage.put("createdByUser", currentUserID);
newMessage.put("text", sendMessageText);
newMessageDb.setValue(newMessage);
}
mSendEditText.setText(null);
}
private void getChatId(){
mDatabaseUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
chatId = dataSnapshot.getValue().toString();
mDatabaseChat = mDatabaseChat.child(chatId);
getChatMessages();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getChatMessages() {
mDatabaseChat.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if(dataSnapshot.exists()){
String message = "";
String createdByUser = "";
if(dataSnapshot.child("text").getValue()!=null){
message = dataSnapshot.child("text").getValue().toString();
}
if(dataSnapshot.child("createdByUser").getValue()!=null){
createdByUser = dataSnapshot.child("createdByUser").getValue().toString();
}
if(message!=null && createdByUser!=null){
Boolean currentUserBoolean = false;
if(createdByUser.equals(currentUserID)){
currentUserBoolean = true;
}
ChatObject newMessage = new ChatObject(message, currentUserBoolean);
resultsChat.add(newMessage);
mChatAdapter.notifyDataSetChanged();
}
}
}
#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) {
}
});
}
private ArrayList<ChatObject> resultsChat = new ArrayList<ChatObject>();
private List<ChatObject> getDataSetChat() {
return resultsChat;
}
}

viewPager Adapter not being updated

I am trying to update adapter(MyCollegePagerAdapter) from CollegeHTMLParse.class. However, even though I created an object and called the notifyDataSetChanged() method on it, noting is showing up on the fragments. Can you tell me if there is anything wrong with my code as I have googled for solution for weeks now and after trying for hours upon hours, I am not able to figure out the issue.
Here is the CollegeHTMLParse class:
public class CollegeHTMLParse extends AppCompatActivity {
public static ArrayList<String> colleges = new ArrayList<>();
public static ArrayList<String> accepted = new ArrayList<>();
public static ArrayList<String> link = new ArrayList<>();
public static ArrayList<String> location = new ArrayList<>();
public static ArrayList<String> tuition = new ArrayList<>();
FirebaseDatabase mRef;
DatabaseReference database;
public static ArrayList<String> data = new ArrayList<>();
MyCollegePagerAdapter adapter = new MyCollegePagerAdapter(getSupportFragmentManager());
public void onCreate(String CollegeCode) {
colleges.clear();
accepted.clear();
link.clear();
location.clear();
tuition.clear();
mRef = FirebaseDatabase.getInstance("https://successway18.firebaseio.com/");
database = mRef.getReference().child("CollegeCodes").child("30");
database.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
setCollegeValues(dataSnapshot.getKey());
}
#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) {
}
});
}
public void setCollegeValues(String values) {
colleges.add(values);
int i = 0;
while (i < colleges.size()) {
database.child(colleges.get(i)).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
setDetailsValues(dataSnapshot.getValue().toString());
}
#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) {
}
});
i++;
}
}
private void setDetailsValues(String details) {
data.add(details);
if (data.size() == 4) {
accepted.add(data.get(0));
link.add(data.get(1));
location.add(data.get(2));
tuition.add(data.get(3));
data.clear();
}
update();
}
private void update() {
adapter.notifyDataSetChanged();
}
}
Thank you very much in advance!
Add this in your pager adapter
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
Firebase query runs in the worker thread, so you have to run notifyDataSetChanged in the main thread.
Try to use the below code in the function update()
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});

How to get list of tokens from firebase database?

In below code I am getting list of users by their blood type and locality. This is working very fine. I want to get a list of their tokens. So how can I do that. I try using firebaseRecyclerAdapter.getItemCount() and a loop but it did not help. So what should I do now? I want to put token in an string array.
public class SearchActivity extends AppCompatActivity {
private Toolbar mToolbar;
private String bloodgroup;
private String locality;
private RecyclerView allUsersList;
private Query allDatabaseUserReference;
private String[] TokenList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
bloodgroup = getIntent().getStringExtra("bt");
locality = getIntent().getStringExtra("pa");
allDatabaseUserReference = FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("user_search").equalTo(bloodgroup + ", " + locality);
mToolbar = (Toolbar) findViewById(R.id.search_activity_app_bar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Search Result");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
allUsersList = (RecyclerView) findViewById(R.id.all_users_list);
allUsersList.setHasFixedSize(true);
allUsersList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<AllUsers,AllUsersViewHolder> firebaseRecyclerAdapter
= new FirebaseRecyclerAdapter<AllUsers, AllUsersViewHolder>
(
AllUsers.class,
R.layout.all_users_display_layout,
AllUsersViewHolder.class,
allDatabaseUserReference
)
{
#Override
protected void populateViewHolder(AllUsersViewHolder viewHolder, AllUsers model, final int position) {
viewHolder.setUser_name(model.getUser_name());
viewHolder.setUser_blood(model.getUser_blood());
viewHolder.setUser_mobile(model.getUser_mobile());
viewHolder.setUser_thumb_image(getApplicationContext(),model.getUser_thumb_image());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
String visit_user_id = getRef(position).getKey();
Intent profileIntent = new Intent(SearchActivity.this, ProfileActivity.class);
profileIntent.putExtra("visit_user_id",visit_user_id);
startActivity(profileIntent);
}
});
}
};
allUsersList.setAdapter(firebaseRecyclerAdapter);
}
public static class AllUsersViewHolder extends RecyclerView.ViewHolder
{
View mView;
public AllUsersViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setUser_name(String user_name)
{
TextView name = (TextView) mView.findViewById(R.id.all_users_username);
name.setText(user_name);
}
public void setUser_blood(String user_blood)
{
TextView blood = (TextView) mView.findViewById(R.id.all_users_blood);
blood.setText(user_blood);
}
public void setUser_mobile(String user_mobile)
{
TextView mobile = (TextView) mView.findViewById(R.id.all_users_phone);
mobile.setText(user_mobile);
}
public void setUser_thumb_image(Context ctx, String user_thumb_image)
{
CircleImageView thumb_image = (CircleImageView) mView.findViewById(R.id.all_users_profile_image);
Picasso.with(ctx).load(user_thumb_image).placeholder(R.drawable.default_profile).into(thumb_image);
}
}
}
you can do it by applying childEventListner on your reference allDatabaseUserReference
allDatabaseUserReference.addChildEventListener(childEventListener);
and here's your childEventListener
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if(dataSnapshot!=null){
if(dataSnapshot.hasChild("device_token")){
tokenList.add(dataSnapshot.child("device_token").getValue().toString());
}
}
}
#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) {}
};

How to transfer data that are stored in TextView in an activity for calculation in another activity?

This is my DisplayBooks class:
public class DisplayBooks extends AppCompatActivity
private FirebaseAuth myAuth;
private DatabaseReference myDatabase;
private TextView book1display,book2display,book3display,book4display,book5display,book6display,book7display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_books);
myAuth = FirebaseAuth.getInstance();
myDatabase = FirebaseDatabase.getInstance().getReference();
book1display = (TextView) findViewById(R.id.book1display);
book2display = (TextView) findViewById(R.id.book2display);
book3display = (TextView) findViewById(R.id.book3display);
book4display = (TextView) findViewById(R.id.book4display);
book5display = (TextView) findViewById(R.id.book5display);
book6display = (TextView) findViewById(R.id.book6display);
book7display = (TextView) findViewById(R.id.book7display);
String user_id = myAuth.getCurrentUser().getUid();
DatabaseReference userid_database = myDatabase.child(user_id);
DatabaseReference book1 = userid_database.child("Books").child("Book 1").child("Page");
DatabaseReference book2 = userid_database.child("Books").child("Book 2").child("Page");
DatabaseReference book3 = userid_database.child("Books").child("Book 3").child("Page");
DatabaseReference book4 = userid_database.child("Books").child("Book 4").child("Page");
DatabaseReference book5 = userid_database.child("Books").child("Book 5").child("Page");
DatabaseReference book6 = userid_database.child("Books").child("Book 6").child("Page");
DatabaseReference book7 = userid_database.child("Books").child("Book 7").child("Page");
book1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book1display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
book2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book2display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
book3.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book3display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
book4.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book4display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
book5.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book5display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
book6.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book6display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
book7.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text = dataSnapshot.getValue(String.class);
book7display.setText(text);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Below is an example output. I want to get the numbers that in the picture for make a calculation in the another activity.
This is my other activity:
public class HowMuch extends AppCompatActivity
private TextView howmuch1,howmuch2;
TextView hay;
Button button2;
private DatabaseReference myDatabase;
private FirebaseAuth myAuth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_how_much);
myAuth=FirebaseAuth.getInstance();
myDatabase= FirebaseDatabase.getInstance().getReference();
howmuch1=(TextView)findViewById(R.id.howmuch1);
howmuch2=(TextView)findViewById(R.id.howmuch2);
hay=(TextView)findViewById(R.id.hay);
String user_id= myAuth.getCurrentUser().getUid();
DatabaseReference userid_database=myDatabase.child(user_id);
DatabaseReference book1=userid_database.child("Books").child("Book 1").child("Page");
DatabaseReference book2=userid_database.child("Books").child("Book 2").child("Page");
book1.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
String text= dataSnapshot.getValue(String.class);
int value=Integer.parseInt(text);
int value1=value/2;
String x= String.valueOf(value1);
howmuch1.setText(x);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
If I write like that for book2, book3 etc. I can make calculattion but I also want to make sum of these values. Hovewer, I couldn't transfer values of them to make new calculation. I tried to transfer values from my DisplayBooks activity writing this:
public void transfer(View view){
String value = book1display.getText().toString();
Intent intent = new Intent(DisplayBooks.this, HowMuch.class);
intent.putExtra("key",value);
startActivity(intent);
}
And adding this to HowMuch class:
String value = getIntent().getExtras().getString("key");
hay.setText(value);
But it didn't work.
It should be
String value = getIntent().getStringExtra("key");
hay.setText(value);
Edit: links for reference:
Send data
https://developer.android.com/training/sharing/send.html
Receive data https://developer.android.com/training/sharing/receive.html
Bundle receivedBundle = getIntent().getExtras();
if (receivedBundle != null) {
String extraString = receivedBundle.getString("key");
int extraInt = receivedBundle.getInt("key");
}

Categories

Resources