Firebase get all child values and store in an array - java

I need to get all child "answer" values from the database into an array.
Afterwards, I want to match that array with another array. I am new to coding, i require help.
My Database is linked here.
I tried it with my code below, but I think my logic is wrong and I cant match the stringArray with the ProductArray.
public class Activity extends AppCompatActivity {
private String[] stringArray = new String[3];
private String[] ProductArray = new String[]{"traveling","short","not much"};
private TextView productTwo;
private DatabaseReference mRef;
private int mQuestionNumber = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recommendations);
productTwo = (TextView) findViewById(R.id.recommendations_product2);
mRef = FirebaseDatabase.getInstance().getReference().child("BTSpeakers").child(String.valueOf(mQuestionNumber));
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
String Answer = dataSnapshot.child("answer").getValue().toString();
//Store Answer values of Database in Array
stringArray[mQuestionNumber] = Answer;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mQuestionNumber++;
//If array values equals ProductArray then , setText To Product2
if(ProductArray.equals(stringArray))
{
productTwo.setText("Speakers");
}
}
}

It is more efficient if you use list instead of array, in your case you can do the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recommendations);
productTwo = (TextView) findViewById(R.id.recommendations_product2);
List<String> productList = new ArrayList<String>();
list.add("traveling");
list.add("short");
list.add("not much");
List<String> answerList = new ArrayList<String>();
mRef = FirebaseDatabase.getInstance().getReference().child("BTSpeakers");
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
for(DataSnapshot ds : dataSnapshot.getChildren()){
String answer = ds.child("answer").getValue().toString();
answerList.add(answer);
if(productList.equals(answerList)){
productTwo.setText("Speakers");
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
First, add the elements inside the list, then add a reference to your parent node BtSpeakers, then loop inside your datasnapshot and retrieve all the answers.

Related

Importing data from the Firebase does not appear in the textview

The data from the Realtime Database Firebase does not appear in textview. I've looked for similar problems here, but I haven't solved them. I'd appreciate it if you could help me solve this problem.
firebase structure:
"state" : {
"open_close" : "open",
"weight" : 2500
}
java code:
public class SubActivity extends AppCompatActivity {
TextView tvWeight;
TextView tvOpen_close;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
tvWeight = findViewById(R.id.textView_weight);
tvOpen_close = findViewById(R.id.textView_open_close);
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("state");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String value = dataSnapshot.child("open_close").getValue(String.class);
int weight = dataSnapshot.child("weight").getValue(int.class);
tvWeight.setText(weight);
tvOpen_close.setText(value);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
There is no need of for loop ,you can directly access it like this.
public class SubActivity extends AppCompatActivity {
TextView tvWeight;
TextView tvOpen_close;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
tvWeight = findViewById(R.id.textView_weight);
tvOpen_close = findViewById(R.id.textView_open_close);
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("state");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String value = dataSnapshot.child("open_close").getValue(String.class);
int weight = dataSnapshot.child("weight").getValue(int.class);
tvWeight.setText(weight);
tvOpen_close.setText(value);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
String value = snapshot.child("open_close").getValue(String.class);
int weight = snapshot.child("weight").getValue(Integer.class);
You are already iterating over children from your snapshot. You don't need to get to the parent snapshot to get child values. Use the iterated value of your snapshot and get values from it. Change your code to above.
Edit
Also if you don't have many nodes same as state I don't see any point of iterating over children.
If your database contain only one node as
`"state" : {
"open_close" : "open",
"weight" : 2500
}`
then don't iterate over it. Just call it directly as below:
final DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String value = dataSnapshot.child("state").child("open_close").getValue(String.class);
int weight = dataSnapshot.child("state").child("weight").getValue(Integer.class);
tvWeight.setText(weight);
tvOpen_close.setText(value);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Add extra data to recyclerView

I've just recently started to learn some coding, a little python and java.
I'm trying to make a whatsapp clone as a test, and I've hit a wall.
Basically I have a UID showing as the name of a group chat, and I want to swap it for a groupId I have saved in firebase at the same level as the Uid.
FirebaseDatabase.getInstance().getReference().child("chat").child(chatId).child("info").child("groupId)
I've been following simcoder youtube video and there's a lot of checks and balances happening between user and chat UIDs and I'm getting lost in the middle of all that.
I've tried adding groupId to the adapter and the chatObject, and I can see the data in debug, but I just can't get it to populate the recycler view. I've had a search of the forums here, but can't quite get it to work.
I'm hoping someone can help me out, many thanks
private RecyclerView mChatList;
private RecyclerView.Adapter mChatListAdapter;
private RecyclerView.LayoutManager mChatListLayoutManager;
ArrayList<ChatObject> chatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_group_chat);
OneSignal.startInit(this).init();
OneSignal.setSubscription(true);
OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() {
#Override
public void idsAvailable(String userId, String registrationId) {
FirebaseDatabase.getInstance().getReference().child("user").child(FirebaseAuth.getInstance().getUid()).child("notificationKey").setValue(userId);
}
});
OneSignal.setInFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification);
Button mLogout = findViewById(R.id.logout);
Button mFindUser = findViewById(R.id.finduser);
mFindUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), FindUserActivity.class));
}
});
mLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OneSignal.setSubscription(false);
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return;
}
});
getPermissions();
initializeRecyclerView();
getUserChatList();
}
private void getUserChatList(){
DatabaseReference mUserChatDB = FirebaseDatabase.getInstance().getReference().child("user").child(FirebaseAuth.getInstance().getUid()).child("chat");
mUserChatDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()){
ChatObject mChat = new ChatObject(childSnapshot.getKey());
boolean exists = false;
for (ChatObject mChatIterator : chatList){
if(mChatIterator.getChatId().equals(mChat.getChatId()))
exists = true;
}
if (exists)
continue;
chatList.add(mChat);
getChatData(mChat.getChatId());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getChatData(String chatId) {
DatabaseReference mChatDB = FirebaseDatabase.getInstance().getReference().child("chat").child(chatId).child("info");
mChatDB.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String chatId = "";
if(dataSnapshot.child("id").getValue() != null)
chatId = dataSnapshot.child("id").getValue().toString();
for(DataSnapshot userSnapshot : dataSnapshot.child("users").getChildren()){
for(ChatObject mChat : chatList)
if(mChat.getChatId().equals(chatId)){
UserObject mUser = new UserObject(userSnapshot.getKey());
mChat.addUserToArrayList(mUser);
getUserData(mUser);
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getUserData(UserObject mUser) {
DatabaseReference mUserDb = FirebaseDatabase.getInstance().getReference().child("user").child(mUser.getUid());
mUserDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
UserObject mUser = new UserObject(dataSnapshot.getKey());
if(dataSnapshot.child("notificationKey").getValue() != null)
mUser.setNotificationKey(dataSnapshot.child("notificationKey").getValue().toString());
for(ChatObject mChat : chatList)
for(UserObject mUserIt : mChat.getUserObjectArrayList()){
if(mUserIt.getUid().equals(mUser.getUid())){
mUserIt.setNotificationKey(mUser.getNotificationKey());
}
}
mChatListAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void initializeRecyclerView() {
chatList = new ArrayList<>();
mChatList = findViewById(R.id.chatList);
mChatList.setNestedScrollingEnabled(false);
mChatList.setHasFixedSize(false);
mChatListLayoutManager = new LinearLayoutManager(getApplicationContext(), RecyclerView.VERTICAL,false);
mChatList.setLayoutManager(mChatListLayoutManager);
mChatListAdapter = new ChatListAdapter(chatList);
mChatList.setAdapter(mChatListAdapter);
}
From what I see you are passing to the adapter an empty list so that's why there's not data to be displayed.
And also, where you are using mChatListAdapter.notifyDataSetChanged();, you don't set before a populated list to the adapter.
I'm not sure which is the data you want to display but you have to collect in a list from the firebase all the information you want to display, for example, if UserObject is what you want, you have to make an ArrayList<UserObject>, to add there all the objects, pass it to the adapter and then call adapter.notifyDataSetChanged() .
You can make function in the adapter, like :
public void setData(ArrayList<YourObject> list){
yourAdapterList = list
this.notifyDataSetChanged()
}
And then call it from your activity/fragment like adapter.setData( /* your populated list */)

Firebase does not work at the first time?

I want to generate a report pdf counting on total Orders and orders with status wanted
I have this code to create pdf and fill table out
private TemplatePDF templatePDF;
FirebaseDatabase database;
DatabaseReference reference;
Button btnRatio1;
ArrayList<String[]> rowqa=new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reportes);
database=FirebaseDatabase.getInstance();
reference=database.getReference("Requests");
btnRatio1=findViewById(R.id.Quality);
btnRatio1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reference.orderByChild("date").startAt("1530002755582").endAt("1530504865654").
addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
createTemplate(rowqa);
}
});
}
private void showData(DataSnapshot dataSnapshot){
int total=(int)dataSnapshot.getChildrenCount();
int count=0;
String[]row;
for (DataSnapshot myDataSnapshot : dataSnapshot.getChildren())
{
Request rq = myDataSnapshot.getValue(Request.class);
if (rq.getStatuscali().equals("0"))
{
count++;
}
}
row= new String[]{Common.getDate(Long.parseLong("1529945980802")),String.valueOf(count),String.valueOf(total),""+ count/total};
addRow(row);
}
private void createTemplate(ArrayList<String[]> rowqa) {
TemplatePDF templatePDF1 = new TemplatePDF(getApplicationContext());
templatePDF1.openDocument("Quality");
templatePDF1.addTitles("Frutifelles E.I.R.L.","Calidad de pedidos generados","25/06/2018");
templatePDF1.createTable(header,rowqa);
templatePDF1.closeDocument();
templatePDF1.viewPDF();
}
private void addRow(String[]row){
rowqa.add(row);
}
The first time show me my pdf this way
But the second time show me correctly
It seems like first time it doesn't work
just as #Jen Person said, you should put the createTemplate(rowqa) inside the onDataChange callback, else when you click the button at the first time, the rowqa is empty, so createTemplate(rowqa) will get an empty PDF.
an example:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reportes);
btnRatio1=findViewById(R.id.Quality);
btnRatio1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// dateStart, dateEnd should be instance fields
queryData(dateStart, dateEnd);
}
});
}
private void queryData(String dateStart, String dateEnd) {
database=FirebaseDatabase.getInstance();
reference=database.getReference("Requests");
reference.orderByChild("date")
.startAt(dateStart)
.endAt(dateEnd)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
showData(dataSnapshot);
createTemplate(rowqa);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

ArrayList add not working in android

This my code. onooltuud is an ArrayList. I get datas Firebase then add the onooltuud arrayList. But arrayList size 0. Caution incoming data from Firebase. Help me.
public class OnooltActivity2 extends AppCompatActivity implements View.OnClickListener {
ArrayList<String> onooltuud = new ArrayList<String>();`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.onoolt_activity_2);
save = (Button) findViewById(R.id.save);
database = FirebaseDatabase.getInstance();
ref = database.getReference("db").child("davaa").child(String.valueOf(davaaniiNo) + "-iinDavaa");
Query query = ref.orderByChild("onooltDugaar");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int temp = (int) dataSnapshot.getChildrenCount();
Log.i("count", String.valueOf(temp));
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Log.i("snapshot", snapshot.getValue().toString());
Onoolt onoolt = snapshot.getValue(Onoolt.class);
onoolts.add(onoolt.getOnooltDugaar());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(OnooltActivity2.this, "Датаг уншиж чадсангүй: " + databaseError.getCode(), Toast.LENGTH_SHORT).show();
}
});
Log.i("testSize:", String.valueOf(onoolts.size()));
this my code onoolts add not working
It says that the size() of your Arraylist object onooltuud is zero (= 0) because you never add anything to it. You declared your ArrayList like that:
ArrayList<String> onooltuud = new ArrayList<String>();
And when you add elements you use a different name:
onoolts.add(onoolt.getOnooltDugaar());
The names do not correspond: onooltuud vs onoolts.
Delete this line:
onoolts.add(onoolt.getOnooltDugaar());
and put this line:
onooltuud.add(onoolt.getOnooltDugaar());

not be able to retrieve firebase data using addValueEventListener

I am trying to retrieve firebase data using addValueEventListener, but unfortunately i am not be able to get right data.
I have New_Deal_List.java class, and in this class i want to retrieve `public class New_Deal_List extends AppCompatActivity {
ListView lvDealList;
List<NewDeal_Database> dealList;
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference("Expert");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new__deal__list);
lvDealList = (ListView)findViewById(R.id.lvDealList);
dealList = new ArrayList<>();
}
#Override
protected void onStart() {
super.onStart();
rootRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dealList.clear();
for(DataSnapshot dealSnapshot : dataSnapshot.getChildren()){
NewDeal_Database info = dealSnapshot.getValue(NewDeal_Database.class);
dealList.add(info);
}
DealList adapter = new DealList( New_Deal_List.this,dealList);
lvDealList.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(New_Deal_List.this,"Databse error",Toast.LENGTH_SHORT).show();
}
});
}
I am adding data through New_Deal.java by this method
private void AddNewDeal(){
int DealName = Integer.parseInt(etDealName.getText().toString());
String NewDealCategory = etNewDealCategory.getText().toString();
String DishName = etDishName.getText().toString();
String DealDescription = etDealDescription.getText().toString();
if(TextUtils.isEmpty(etDishName.getText().toString()) || TextUtils.isEmpty(etNewDealCategory.getText().toString()) || TextUtils.isEmpty(etDishName.getText().toString()) || TextUtils.isEmpty(etDealDescription.getText().toString())){
Toast.makeText(this,"All fileds must be filled.",Toast.LENGTH_SHORT).show();
}else{
DealId = keyRefrence.push().getKey();
//firebaseDatabase data = new firebaseDatabase(DealName,NewDealCategory,DishName,DealDescription);
//Contact_Info info = new Contact_Info( DealName, NewDealCategory, DealDescription);
NewDeal_Database info = new NewDeal_Database(DealName,NewDealCategory, DishName, DealDescription); keyRefrence.child(Cooker_Deal).child(DealId).child(Deal).setValue(info);
Toast.makeText(this,"Information Added",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(New_Deal.this,New_Deal_Time.class);
startActivity(intent);
}
}
I am setting value using this NewDeal_Databse.java
public NewDeal_Database(int DealName,String NewDealCategory, String DishName, String DealDescription){
this.DealName = DealName;
this.NewDealCategory = NewDealCategory;
this.DishName = DishName;
this.DealDescription = DealDescription;
}
public int getDealName() {
return DealName;
}
public String getNewDealCategory() {
return NewDealCategory;
}
public String getDishName() {
return DishName;
}
public String getDealDescription() {
return DealDescription;
}
Also i DealList.java for array adapter
public class DealList extends ArrayAdapter <NewDeal_Database> {
private Activity context;
private List<NewDeal_Database> dealList;
public DealList(Activity context, List<NewDeal_Database> dealList){
super(context, R.layout.list_layout, dealList);
this.context = context;
this.dealList = dealList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_layout,null,true);
TextView tvDealName = (TextView)listViewItem.findViewById(R.id.tvDealNamelayout);
TextView tvNewDealCategory = (TextView)listViewItem.findViewById(R.id.tvNewDealCategorylayout);
NewDeal_Database info = dealList.get(position);
tvDealName.setText(String.valueOf(info.getDealName()));
tvNewDealCategory.setText(info.getNewDealCategory());
return listViewItem;
}
}
I get these on values on output
Output the data
I this is firebase databse snapshot
firebase datasbe snapshot
updated firebase databse snapshot
Updated output
Problem solved using this code:
#Override
protected void onStart() {
super.onStart();
//dealList.clear();
rootRef.child(id).child(Cooker_Deal).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dealSnapshot : dataSnapshot.getChildren()){
for(DataSnapshot datas : dealSnapshot.getChildren()){ //
NewDeal_Database info = datas.getValue(NewDeal_Database.class);
count++;
if(count>3){
dealList.add(info);
count=0;
}
}
}
DealList adapter = new DealList( New_Deal_List.this,dealList);
lvDealList.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
I think its nested too much but to answer your question, you need to remove this from your code:
dealList.clear();
and add it outside of the addValueEventListener()
like this:
protected void onStart() {
super.onStart();
dealList.clear();
rootRef.addValueEventListener(new ValueEventListener() {
Edit:
#Override
protected void onStart() {
super.onStart();
dealList.clear();
rootRef.child(expertId).child("Cooker Deals").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dealSnapshot : dataSnapshot.getChildren()){
for(DataSnapshot datas : dealSnapshot.getChildren(){
NewDeal_Database info = datas.getValue(NewDeal_Database.class);
dealList.add(info);
}
DealList adapter = new DealList( New_Deal_List.this,dealList);
lvDealList.setAdapter(adapter);
adapter.notifydatasetchanged();
}
Assuming that faum-expert nide is a direct child of your Firebase database, to get that data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("faum-expert").child("Expert").child(expertId).child("Cooker Deals");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String dealName = ds.child("Deals Information").child("dealName").getValue(String.class);
String newDealCategory = ds.child("Deals Information").child("newDealCategory").getValue(String.class);
Log.d("TAG", dealName + " / " + newDealCategory);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(eventListener);
The output will be:
4567 / kagj
But pay atention, the fields inside your model class are first letter uppercase and in your database are first letter lowercase. To solve this, add the following annotations in front of your fields like this:
#PropertyName("dealName")
private String DealName;
#PropertyName("newDealCategory")
private String NewDealCategory;
#PropertyName("dishName")
private String DishName;
#PropertyName("dealDescription")
private String DealDescription;

Categories

Resources