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());
Related
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) {
}
});
Currently, I am writing a social media app, and now I would like to retrieve the datas from my firebase database, where each user has some ratings. mUploads - it stores the uploaded items (photo, name, city, ID).
mDatabaseRef-ratings - it stores the ratings of the uploaded items, (some items don't have ratings yet). They have the same ID, just like in the mUploads->ID
It's actually a big project, and I have retrieved multiple times other type of firebase elements, but this time the addvalueventlistener won't get called, and I couldn't figure it out. Why?
It's not the whole code, but the main part is this. I tried to several ways, but nothing helped. I tried call it not only in this adapter class, but also in my other class, where I retrieve the data for the mUploads list.
...
public class ProfileAdapter extends RecyclerView.Adapter<ProfileAdapter.ImageViewHolder> implements Filterable {
private Context mContext;
private List<Upload> mUploads;
private List<Upload> exampleListFull;
private OnNoteListener mOnNoteListener;
private ArrayList<Ratingsclass> mratings_array;
public float sumofstars, numofratings, defaultstars;
private DatabaseReference mDatabaseRef_ratings;
public ProfileAdapter(Context context, List<Upload> upload, OnNoteListener onNoteListener){//, ArrayList<Ratingsclass> ratinglist){
mContext=context;
mUploads=upload;
exampleListFull=new ArrayList<>(upload);
mOnNoteListener=onNoteListener;
for (int i = 0; i < mUploads.size(); i++){
mDatabaseRef_ratings = FirebaseDatabase.getInstance().getReference("ratings");
Log.d("myTag", "loop");
/*checking if child already exists*/
mDatabaseRef_ratings=mDatabaseRef_ratings.child(mUploads.get(i).getKey());
Log.d("myTag", "ez az id: "+ mUploads.get(i).getKey());
final int finalI = i;
mDatabaseRef_ratings.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
// The child doesn't exist
Log.d("myTag", "has no rating");
}else{
mDatabaseRef_ratings = FirebaseDatabase.getInstance().getReference("ratings").child(mUploads.get(finalI).getKey());
Log.d("myTag", "checking the elements of this child");
mDatabaseRef_ratings.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Ratingsclass temp = new Ratingsclass();
numofratings = 0;
sumofstars = 0;
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
temp = postSnapshot.getValue(Ratingsclass.class);
numofratings += 1;
sumofstars += temp.getNum_of_stars();
Log.d("myTag", numofratings + " es " + sumofstars);
}
if (numofratings == 0)
defaultstars = 0;
else
defaultstars = sumofstars / numofratings;
temp.setRatingid(mUploads.get(finalI).getKey());
temp.setRating_sum(defaultstars);
mratings_array.add(temp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
//
}
});
}
}
... etc
If you pass a listener to the constructor of your adapter onNoteListener you should be listening in your activity/fragment for changes that this interface does.
In your code, inside your adapter you use
mOnNoteListener=onNoteListener;
but you never call the interface to send the values to your view (inside onDataChange(...))
so, what you need to do to get these values is to call your interface to send these values to your view
so, after you fetch the data in Firebase use your callback
mOnNoteListener.yourMethod(your_value);
I could manage to solve, with the help of another topic. I just added this code:
mDatabaseRef_ratings.child("ratings").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot entrySnapshot : dataSnapshot.getChildren()) {
alreadyrated=false;
for (DataSnapshot propertySnapshot : entrySnapshot.getChildren()) {
Log.d("myTag", entrySnapshot.getKey() + " : " + propertySnapshot.getKey());
... etc
This double for loop is enough to get the id of the parent and the id of the child too, so now my rating app is working.
So I made a void function that should put some values in an array . I call the function , then I call the array variable and it crashes saying that its null. I am also using firebase to get all the values .
This is the Function :
private void findRestaurantKey()
{
mDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mDatabase.getReference("x");
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
int i = 0;
for (DataSnapshot d : dataSnapshot.getChildren()) {
allRestNames[i] = d.getKey();
i++;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
And here is how i try to call it :
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_activity);
this.findRestaurantKey();
Log.d("ARRAY" , allRestNames.toString());
}
You need to initialize your array.
List<String> allRestNames = new ArrayList();
But if you run the code as you have it, you would not Log anything
This is what is called a 'race condition', you are running asynchronous code expecting the result to be there as soon as you call it.
When making a request to an API like you are doing using the Firebase service it takes time.
So what you should do if you wanna Log the results is do it in the callback:
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.food_activity);
findRestaurantKey();
}
private void findRestaurantKey() {
mDatabase = FirebaseDatabase.getInstance();
mDatabaseReference = mDatabase.getReference("x");
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot d : dataSnapshot.getChildren()) {
allRestNames.add(d.getKey());
}
// HERE is when the data is available from the Firebase service
Log.d("ARRAY" , allRestNames.toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
You need to initialize your array somewhere:
allRestNames = new String[5000];
Use whatever number is appropriate instead of 5000. If you don't know what size to make the array to begin with, you should use an ArrayList instead of an array.
Also, findRestaurantKey() creates a listener for your Firebase database. When this method returns, the data is not yet available because the listener has not yet been called. So even if you solve the current error, you will not get any meaningful data from calling allRestNames.toString() in onCreate().
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.
This is my code in main, retrieving set of values from firebase
List<model> weather = new ArrayList<model>();
Query dbQuery = FirebaseDatabase.getInstance().getReference().child("NeuralNetwork");
dbQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//Model
model m = dataSnapshot.getValue(model.class);
int prev = m.getPrevious();
int hu = m.getHumidity();
int tem = m.getTemperature();
int wi = m.getWind();
int nw = m.getNewValue();
Toast.makeText(MainActivity.this, "value of temp" + temp, Toast.LENGTH_SHORT).show();
weather.add(new model(prev, tem, hu, wi, nw));
}
I have to retrieve all the values in an arraylist weather. The image shows my firebase, I have to loop through the nodes and get the child values:
I hope you define model class constructor and also get data used below code:
private DatabaseReference mDatabase;
private FirebaseDatabase mFirebaseInstance;
// put below two line in onCreate method.
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mDatabase.addValueEventListener(new ValueEventListener() { // here pass your firebase database instance..
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
weather.clear();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
model model = postSnapshot.getValue(model.class);
weather.add(model);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});