after taking data with takeModel in OnDataChange() I want to put them into arraylist, which is resposinble for creating activity.
final String[] takeModel = null;
....
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i=0;
int lenght = (int) dataSnapshot.getChildrenCount();
String[] takeModel = new String[lenght];
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
TvAtributes tvnowe = postSnapshot.getValue(TvAtributes.class);
takeModel[i]=tvnowe.getModel(); // taking data here
i++;
}
}
......
ArrayList<TvAtributes> tv_models = new ArrayList<>();
for(int i=0;i<android_version_names.length;i++){
TvAtributes tvModele = new TvAtributes();
tvModele.setModel(takeModel[i]); //this is crashing
tvModele.setImgaddres(image_urls[i]);
tv_models.add(tvModele);
I have no clue what to do.
Thanks in advance
The answer is
final ArrayList<TvAtributes> tv_models = new ArrayList<>();
.....
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int i=0;
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
TvAtributes tvnowe = postSnapshot.getValue(TvAtributes.class);
tvnowe.getModel();
tvnowe.setImgaddres(image_urls[i]);
tv_models.add(tvnowe);
i++;
}
...
return tv_models;
Thanks for help
Related
I want to ask about how to limit retrieve data in Android Firebase. Here is my code:
private void lookingforHelp(){
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference("Locations");
dbref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
int limitUser = 0;
ModelUsersLocation mUserLoct = ds.getValue(ModelUsersLocation.class);
LatLng yourLatLng = new LatLng(latitude_user, longitude_user);
LatLng polisiLatLng = new LatLng(mUserLoct.getLatitude(), mUserLoct.getLongitude());
if (mUserLoct.getPengguna().equals("polisi")){
if (SphericalUtil.computeDistanceBetween(yourLatLng, polisiLatLng) < 700) {
if (limitUser <= 5){
if (mUserLoct.getJangkauan().isEmpty()) {
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference("Locations").child(mUserLoct.getUser().getUid());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("jangkauan", fuser.getUid());
dbref.updateChildren(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
writeNewOrder();
}
});
}
}
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
I tried to retrieve data that i want is only less than 5 users, using int limitUser = 0; and it's still not working to retrieve data only less than 5 users.
PROBLEM SOLVED, I try to create markeroptions and make it into invisible, and then add it into arraylist, if (markers.size() <= 5) {do something}
thank u guys for your help btw i really apreciate it :))
public MutableLiveData<ArrayList<Vendor>> getVendorsByLimit(int limit) {
ArrayList<Vendor> arrayList = new ArrayList<>();
Query query = FirebaseDatabase.getInstance().getReference().child("VENDOR_NODE").limitToLast(limit);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getChildrenCount() > 0) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
if (snapshot.getChildrenCount() > 0) {
//String value = (String) snapshot.getValue(); //Get all child data
//OR
//String singleValue = (String) snapshot.child("fullName").getValue(); //Get single child data
Vendor model = snapshot.getValue(Vendor.class);
String key = snapshot.getKey();
arrayList.add(model);
}
}
data.setValue(arrayList);
} else {
data.setValue(null);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.e(TAG, "" + databaseError.getMessage());
data.setValue(null);
}
});
}
Query query = FirebaseDatabase.getInstance().getReference().child("VENDOR_NODE").limitToLast(limit);
You can sort them by using timeStamp like
-----------------------------------------
FirebaseDatabase.getInstance().getReference()
.child("Conversation").child(conversationID)
.limitToLast(100)
.orderByChild("timestamp")
.startAt(dateToStart) // pass timestamp from when you want to start filtering
.endAt(dateToEnd); // pass timestamp till when you want to apply filtering
I am using firebase database to retrieve user data into my android studio application. I am looking to sum all of the numbers under the child ("BlueCount") together to get an all time total. I am having trouble retrieving all the "BlueCount" data from each different date.
I am trying to add all the underlined "BlueCount" values together.
I have tried this but i can only retrieve data from the current date...
private TextView blueValue;
private TextView redValue;
private TextView greenValue;
private TextView yellowValue;
private ArrayList<Integer> blist = new ArrayList<>();
private ArrayList<Integer> rlist = new ArrayList<>();
private ArrayList<Integer> glist = new ArrayList<>();
private ArrayList<Integer> ylist = new ArrayList<>();
private ArrayList<Integer> bblist = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dataview);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
blueValue = (TextView)findViewById(R.id.blueValue);
redValue = (TextView)findViewById(R.id.redValue);
greenValue = (TextView)findViewById(R.id.greenValue);
yellowValue = (TextView)findViewById(R.id.yellowValue);
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null){
return;
}
final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
final Date date = new Date();
String userID = user.getUid();
String strDate = dateFormat.format(date);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = database.getReference();
databaseReference.child("users")
.child(userID)
.child(strDate)
.child("BlueCount").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
int num = 0;
String holder = String.valueOf(dataSnapshot.getValue());
num += Integer.parseInt(holder.trim());
blist.add(num);
int sum = 0;
for (int counter=0;counter<blist.size();counter++){
sum+= blist.get(counter);
}
blueValue.setText(" "+sum);
}
#Override
public void onChildChanged(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onChildRemoved(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Firebase can only load complete nodes, or nodes that can be queries. So you'll have to load all data, and then loop over each level to determine the totals.
Something like this should do the trick:
DatabaseReference databaseReference = database.getReference();
DatabaseReference userReference = databaseReference.child("users").child(userID);
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long totalBlueCount = 0;
for (DataSnapshot yearSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot monthSnapshot: yearSnapshot.getChildren()) {
for (DataSnapshot daySnapshot: monthSnapshot.getChildren()) {
DataSnapshot blueSnapshot = daySnapshot.child("BlueCount");
long dayBlueCount = 0;
for (DataSnapshot daySnapshot: monthSnapshot.getChildren()) {
long count = Long.parseLong(daySnapshot.getValue(String.class));
dayBlueCount += count;
}
System.out.println(yearSnapshot.getKey()+"-"+monthSnapshot.getKey()+"-"+daySnapshot.getKey()+": blue count = "+dayBlueCount);
totalBlueCount += dayBlueCount;
}
}
}
System.out.println("Total blue count = "+totalBlueCount);
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
I would consider if the hierarchy really helps you here, as the code would be a lot simpler if each day was just at the same level under a user "2019-07-16", "2019-07-17", etc.
I want to make a filtering method in my application. So, I want to display all the city from the firebase database inside my spinner without display the same city. For your information, the city is in the EditText field.
My coding:-
private void loadFireBaseDataList(final String referenceKey)
{
databaseReference = FirebaseDatabase.getInstance().getReference(referenceKey);
databaseReference.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
final List<String> identity2 = new ArrayList<String>();
identity2.add(0, "Location");
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
for (DataSnapshot dataSnapshot2 : snapshot.getChildren())
{
identity2.add(dataSnapshot2.child("adstuitioncity").getValue(String.class));
}
}
ArrayAdapter<String> nameAdapter2 = new ArrayAdapter<String>(FilterTuitionCentre.this, android.R.layout.simple_spinner_item, identity2);
nameAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spLocation.setAdapter(nameAdapter2);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
My database:-
My interface output:-
You could use Set<String> which contains no duplicates:
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Set<String> cities = new HashSet<String>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
// ...
cities.add(value)
}
List<String> identity2 = new ArrayList<String>(cities);
identity2.add(0, "Location")
ArrayAdapter<String> adapter = new ArrayAdapter<String>(FilterTuitionCentre.this, android.R.layout.simple_spinner_item, identity2);
// ...
}
I would like to retrieve all errand names which are child nodes of a child node in my Firebase DB.
However, I am only able to reference until the 2nd child node(the random key)
Here is my code;
View view = inflater.inflate(R.layout.tab1,container,false);
String r = "Errands";
root = FirebaseDatabase.getInstance().getReference().child(r);
list = (ListView) view.findViewById(R.id.mylistview);
arrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,list_of_errands);
list.setAdapter(arrayAdapter);
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()) {
set.add(((DataSnapshot) i.next()).getKey());
}
Kindly Assist
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference errandsRef = rootRef.child("Errands");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
DatabaseReference keyRef = rootRef.child("Errands").child(key);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String Errand = ds.child("Errand").getValue(String.class);
Log.d("TAG", Errand);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
keyRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
errandsRef.addListenerForSingleValueEvent(eventListener);
And your output will be:
Go to Strath
//and so on
Hope it helps.
I have a list called "categories" and I need to compare each entry of that list to the "cat" attribute of all the entries in my Firebase. If they match, I retrieve the data. So each entry of the list will match several entries in my database and I need to retrieve all those entries at once.
Here is the code I'm trying to use but it isn't working
final static List<String> categories = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
for (int j = 0; j < categories.size(); j++){
databaseReference.child("Advertiser").orderByChild("cat").equalTo(categories.get(j)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final ArrayList<DataSnapshot> dataSnapshots = new ArrayList<>();
for (DataSnapshot snapshot: dataSnapshots){
final String cat = snapshot.child("cat").getValue(String.class);
//etc..
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
EDIT
This is the code I'm using to retrieve info about the liked pages and populating the List categories
public static void getLikedPageInfo(LoginResult login_result){
GraphRequest data_request = GraphRequest.newMeRequest(
login_result.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json_object, GraphResponse response) {
try {
// convert Json object into Json array
JSONArray posts = json_object.getJSONObject("likes").optJSONArray("data");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
//String id = post.optString("id");
String category = post.optString("category");
String name = post.optString("name");
//int count = post.optInt("likes");
if (!categories.contains(category)){
categories.add(category);
}
Log.e("name: ", name+" category: "+category);
}
Log.e("category", categories.toString());
} catch(Exception e){
}
}
});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "likes{id,category,name,location,likes}");
data_request.setParameters(permission_param);
data_request.executeAsync();
}
You're looping over an empty ArrayList
public void onDataChange(DataSnapshot dataSnapshot) {
// You create a new ArrayList and then loop over it without actually putting anything in there.
final ArrayList<DataSnapshot> dataSnapshots = new ArrayList<>();
for (DataSnapshot snapshot: dataSnapshots){
final String cat = snapshot.child("cat").getValue(String.class);
//etc..
}
}
This should do the trick.
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
final String cat = snapshot.child("cat").getValue(String.class);
//etc..
}
}
Does this work?
public static void getLikedPageInfo(LoginResult login_result){
GraphRequest data_request = GraphRequest.newMeRequest(
login_result.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json_object, GraphResponse response) {
try {
// convert Json object into Json array
JSONArray posts = json_object.getJSONObject("likes").optJSONArray("data");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
//String id = post.optString("id");
String category = post.optString("category");
String name = post.optString("name");
//int count = post.optInt("likes");
if (!categories.contains(category)){
categories.add(category);
databaseReference.child("Advertiser").orderByChild("cat").equalTo(category).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot advertiser : dataSnapshot.getChildren()) {
final String categoryString = advertiser.child("cat").getValue(String.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Log.e("name: ", name+" category: "+category);
}
Log.e("category", categories.toString());
} catch(Exception e){
}
}
});
Bundle permission_param = new Bundle();
permission_param.putString("fields", "likes{id,category,name,location,likes}");
data_request.setParameters(permission_param);
data_request.executeAsync();
}