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) {
}
});
Related
I need you to help me to solve this problem:
The problem is that I want to read a String called coins from the database of Firebase and then turn it into an Integer value. Then when I push a button I want to add 1 to coins and after that, I turn it back into a String value to save it in the database.
So I tried to do this by using onDataChange to read the data and then use
int score = Integer.parseInt(coins) to turn it into an Integer value called score.
After that, I used onClickListener to add 1 to the integer, but Android Studio tells me:
Cannot resolve score
I don't know how to solve this issue so I would be so happy if you could help me with that thing.
This is my code :
public class HomeFragment extends Fragment {
public HomeFragment() {
// Required empty public constructor
}
//firebase
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference storageReference;
//init view
ImageButton addCoinsBtn;
TextView coinsTv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =inflater.inflate(R.layout.fragment_home, container, false);
//init firebase
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
storageReference = getInstance().getReference();//firebase storage reference
coinsTv=(TextView)view.findViewById(R.id.coinsTv);
addCoinsBtn=(ImageButton)view.findViewById(R.id.add_coins);
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//check until required data get
for (DataSnapshot ds : dataSnapshot.getChildren()){
//get data
String coins = ""+ds.child("coins").getValue();
int score = Integer.parseInt(coins);
//set data
coinsTv.setText(score);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
addCoinsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference coins = database.getReference("Users/"+ user.getUid() +"/coins");
Integer score = score + 1;
String scorefinal = Integer.toString(score);
coins.setValue(scorefinal);
}
});
return view;
}
}
Thank you very much for all your bits of help.
This is a basic scoping problem: variables only exist in the scope where you declare them.
So the int score that you declare in onDataChange is not available in the onClick method anymore.
And the Integer score that you declare in onClick is a new variable, which means that Integer score = score + 1; won't work, because the score on the right-hand side doesn't exist/have a value.
The solution is to declare score one level higher, as a member field of your `` class:
Integer score = -1;
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
String coins = ""+ds.child("coins").getValue();
score = Integer.parseInt(coins);
coinsTv.setText(score);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
addCoinsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference coinsRef = database.getReference("Users/"+ user.getUid() +"/coins");
score = score + 1;
String scorefinal = Integer.toString(score);
coinsRef.setValue(scorefinal);
}
});
I'd highly recommend storing the value as a number in the database, as it saves you constantly converting from string to integer and back. If you do this, the above code becomes:
Integer score = -1;
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
score = ds.child("coins").getValue(Integer.class);
coinsTv.setText(score);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // never ignore errors
}
});
addCoinsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference coinsRef = database.getReference("Users/"+ user.getUid() +"/coins");
coinsRef.setValue(score+1);
}
});
I need to get data from a table and use it as a reference in order to get another data in another table.
Here is my table structure
Here is how I get the data in java class.IN my table, I have stored an attribute called 'theraid' which I need to retrieve it and use it as a reference in order to get another attribute named 'name' in another table.
a=new ArrayList<AppointmentObject>();
namelist=new ArrayList<String>();
databaseReference= FirebaseDatabase.getInstance().getReference().child("appointment");
databaseReference.orderByChild("userid").equalTo(userid1).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()) {
AppointmentObject thera= dataSnapshot1.getValue(AppointmentObject.class);
a.add(thera);
final String theraid = dataSnapshot1.child("theraid").getValue().toString();
refThera = FirebaseDatabase.getInstance().getReference().child("alluser").child("thera");
refThera.child(theraid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot3) {
for (DataSnapshot ds: dataSnapshot3.getChildren())
{
***************error this line below********************************
String text = ds.child("name").getValue().toString();
namelist.add(text);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "Oh no!", Toast.LENGTH_SHORT).show();
throw databaseError.toException();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "Oh no!", Toast.LENGTH_SHORT).show();
}
});
adapter=new MyRecyclerviewPAppointment(MainActivityPAppointment.this, a,namelist);
rv.setAdapter(adapter);
Here is the recyclerview class in order to display the data that retrieve via the java class.
public class MyRecyclerviewPAppointment extends RecyclerView.Adapter<MyRecyclerviewPAppointment.MyViewHolder> {
private Context context;
ArrayList<AppointmentObject> alist;
ArrayList<String> namelist1;
public MyRecyclerviewPAppointment(Context c, ArrayList<AppointmentObject> t,ArrayList<String> namelist) {
context = c;
alist = t;
namelist1=namelist;
}
#Override
public void onBindViewHolder(#NonNull final MyRecyclerviewPAppointment.MyViewHolder holder,final int position) {
holder.tdate.setText(alist.get(position).getDate());
holder.ttime.setText(alist.get(position).getTiming());
holder.tname.setText(namelist1.get(position));
// holder.tstatus.setText(alist.get(position).getTiming());
}
#Override
public int getItemCount() {
return alist.size();
}
}
I don't know what's wrong to my code but it can't work, it just keeps stopped.
Here is the error. May I know where is the mistake in my d=code? Thanks for helping me :).
In the second listener, your databaseReference is at node theraid. Therefore you don't have to loop to be able to access the value of name. So change the following code:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot3) {
for (DataSnapshot ds: dataSnapshot3.getChildren()) {
String text = ds.child("name").getValue().toString();
namelist.add(text);
}
}
Into this:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot3) {
String text = dataSnapshot3.child("name").getValue().toString();
namelist.add(text);
}
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.
I want to fetch a specific data from Firebase dynamically. This is my structure:
Getting the "Cashier" value of 2 in this image is like this:
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference databaseReferenceMyCurrentQueue = firebaseDatabase.getReference("Cashier");
databaseReferenceMyCurrentQueue.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String queuedNumber = String.valueOf(dataSnapshot.getValue());
currentqueue1.setText(queuedNumber);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
How can I make the realtime fetched value of myCurrentQueue from 5 to 6 after deleting the first child of cashier transactions containing the myCurrentQueue of value 5? Thanks in advance.
So every delete, the realtime myCurrentQueue will change as well.
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
final DatabaseReference databaseReferenceMyCurrentQueue = firebaseDatabase.getReference("CashierTransaction");
databaseReferenceMyCurrentQueue.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//get Data as hashMap<String, YourClass>
//then check the lowest number and update the queue
firebaseDatabase.getReference("Cashier").setValue(ThatNumber);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
final DatabaseReference databaseReferenceMyCurrentQueue = firebaseDatabase.getReference("Cashier");
databaseReferenceMyCurrentQueue.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String queuedNumber = String.valueOf(dataSnapshot.getValue());
currentqueue1.setText(queuedNumber);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
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;