retreiving sqlite and firebase data at the same time - java

Im retrieving a UID from sqlite and using that uid to fetch data from firebase but the problem is its only fetching the values of the first UID and not after that
Code
String userId = null;
Cursor csr = myDBHlpr.getAllQuestions4();
while (csr.moveToNext()) {
userId = csr.getString(csr.getColumnIndex(KEY_USER_ID));
}
final String uid = userId;
mUsersDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mName = dataSnapshot.child("Name").getValue().toString();
String mStatus = dataSnapshot.child("Status").getValue().toString();
String mDisplayImage = dataSnapshot.child("Image").getValue().toString();
mUsers.add(new IdHelper(mName, mStatus, mDisplayImage));
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The table has multiple rows with different UIDs and firebase too has multiple UID data... I have crosschecked multiple times. But still only the one item is fetched. Why is that? should i retrieve sqlite data is a string []?
Database ref is perfect and the problem according to me is that im fetching only one data as userid and im thinking it stops there so only one IDs data is getting fetched from firebase. Anyways can someone help me out please
Edit
public Cursor getAllQuestions4() {
return this.getWritableDatabase().query(TABLE_ID_DATA,null,null,null,null,null,null);
}

I guess your problem is the while loop. You are only using the last userId. So change your code as follows (please notice the change of the last bracket of your while loop):
String userId = null;
Cursor csr = myDBHlpr.getAllQuestions4();
while (csr.moveToNext())
{
userId = csr.getString(csr.getColumnIndex(KEY_USER_ID));
final String uid = userId;
mUsersDatabase.child(userId).addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mName = dataSnapshot.child("Name").getValue().toString();
String mStatus = dataSnapshot.child("Status").getValue().toString();
String mDisplayImage = dataSnapshot.child("Image").getValue().toString();
mUsers.add(new IdHelper(mName, mStatus, mDisplayImage));
mAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Related

Update Firebase database data

I am trying to update my databse:
This is my code, but it doesn't seem to update the database. (Write access is set to true in Firebase settings)
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("items").child("1").child("itemAvailability").setValue("Not Available");
Java class
public class Item {
String itemName;
String itemAvailability;
public Item(String itemName, String itemAvailability) {
this.itemName = itemName;
this.itemAvailability = itemAvailability;
}
public Item() {
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemAvailability() {
return itemAvailability;
}
public void setItemAvailability(String itemAvailability) {
this.itemAvailability = itemAvailability;
}
}
You can do something like this with a Map Data structure.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
DatabaseReference itemRef = ref.child("items/1/itemAvailability");
Map<String, Object> itemUpdates = new HashMap<>();
itemUpdates.put("itemAvailability", "Not Available");
itemRef.updateChildrenAsync(itemUpdates);
This will take the item 1's availability and update it's availability to Not Available
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("items").child("1").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
HashMap<String, Object> updateMap = new HashMap<>();
updateMap.put("itemAvailability", "Not Available");
ref.updateChildren(updateMap);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Might work for you.
Here is the code for Firebase real-time database Insert, Update & Delete operation(CRUD).
//****UPDATE
var database = firebase.database();
let userRef = database.ref('myroot/items/');
userRef.child("1").child("itemAvailability").update("Not Available").then().catch();
//****Insert
var database = firebase.database();
let userRef = database.ref('myroot/items/');
userRef.child("1").child("itemAvailability").set("Not Available").then().catch();
//****Delete
let itemId=1;
let userRef = database.ref('myroot/items/' + itemId);
userRef.remove().then().catch();

How to create condition inside the datasnapshot/recyclerview in Android Studio?

I created tabbed activity for my project. I have three tabs which are Paid , Unpaid and Item Posted
I want to classify every of them based on the status. I have created the coding but I'm not sure on how to implement the method inside my coding. I want only order that have "PAID" as their status will be shown up inside my PaidFrag.
PaidFrag:
databaseReference = FirebaseDatabase.getInstance().getReference("Order");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
orderList = new ArrayList<>();
for (DataSnapshot orderSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot ds : orderSnapshot.getChildren()) {
Order order = ds.getValue(Order.class);
if (order.getStatus().equals("UNPAID")) ;
orderList.add(ds.getValue(Order.class));
}
}
psOrderAdapter PsOrderAdapter = new psOrderAdapter(orderList);
recyclerView.setAdapter(PsOrderAdapter);
}
}
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, final int i) {
myViewHolder.name.setText("Name : " + orderList.get(i).getName());
myViewHolder.status.setText("Status : " + orderList.get(i).getStatus());
myViewHolder.total.setText("Total Price : RM " + orderList.get(i).getTotal());
myViewHolder.address.setText("Address : " + orderList.get(i).getAddress());
myViewHolder.dateTime.setText("Order ID :" + orderList.get(i).getOrder_id());
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String cust_id = orderList.get(i).getCust_id();
String oid = orderList.get(i).getOrder_id();
String status = orderList.get(i).getStatus();
String courier = orderList.get(i).getCourier();
String track = orderList.get(i).getTrackingNum();
String num = orderList.get(i).getPhone();
Intent intent = new Intent(context, updateStatus.class);
intent.putExtra("cust_id",cust_id);
intent.putExtra("order_id",oid);
intent.putExtra("status",status);
intent.putExtra("courier", courier);
intent.putExtra("trackingNum",track);
intent.putExtra("phone",num);
context.startActivity(intent);
}
});
It sounds like you're looking for a Firebase Database query, which limits what nodes are returns from the database:
databaseReference = FirebaseDatabase.getInstance().getReference("Order");
Query query = databaseReference.orderByChild("status").equalTo("PAID");
query.addValueEventListener(new ValueEventListener() {
...
You'll need to make sure that the status and PAID strings match the exact key and value that you have in your database.
For more on this, see the Firebase documentation on ordering and filtering data.

Problem with Firebase adding a fab button cant delete entry

Currently a have a floating action bottom in my detailView in this activity I bring the information of the Object with an intent. I want that when the user enters the detailView activity I have a filled heart if that Automoviles objectId already exist in the Favorites Node.if not add the information into the Database. If the favorite already exist and it has the filled heart if the user clicks again it will remove it from the database.
This is my favorites class:
public class Favorites {
private String id;
private String automovilesId;
private String userId;
private String fecha;
public Favorites() {
}
public Favorites(String automovilesId, String userId, String fecha) {
this.automovilesId = automovilesId;
this.userId = userId;
this.fecha = fecha;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAutomovilesId() {
return automovilesId;
}
public void setAutomovilesId(String automovilesId) {
this.automovilesId = automovilesId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
}
At the moment i have this code:
databaseReference = FirebaseDatabase.getInstance().getReference(AppModel.Favorites);
favoritesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference usersRef = rootRef.child("Favorites");
favorites = new Favorites(automoviles.getObjectId(), user.getUid(), AppModel.GetDate());
databaseReference.push().setValue(favorites);
}
});
Which Leads this entry in the database:
Firebase Data
This is all good but i need to verify also if favorites exist or not in the database or else everytime i run the android emulator it will create another favorites node.
Now i added more code . But when i run it and i add this AddFavorite method it will create infinite loops of Favorite Nodes in the database
databaseReference = FirebaseDatabase.getInstance().getReference(AppModel.Favorites);
favoritesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference usersRef = rootRef.child("Favorites");
favorites = new Favorites(automoviles.getObjectId(), user.getUid(), AppModel.GetDate());
databaseReference.push().setValue(favorites);
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String car = ds.child("automovilesId").getValue(String.class);
Favorites fav =ds.getValue(Favorites.class);
String carId =fav.getAutomovilesId();
Log.i("No","Este es el nombre------>:"+carId);
String id=ds.getKey();
AddFavoritesuser();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
This is the AddFavorite method and the delete method:
private void AddFavoritesuser() {
favoritesButton.setImageResource(R.drawable.ic_favorite);
favorites = new Favorites(automoviles.getObjectId(), user.getUid(), AppModel.GetDate());
databaseReference.push().setValue(favorites);
}
And the delete:
private void deleteFavoritesUser(String key) {
favoritesButton.setImageResource(R.drawable.ic_favorite_border);
databaseReference.child(key).getRef().removeValue();
}
In short i want it to verify if that object of Automoviles object exist . If it exist the user enters and sees the filled heart, if he wants to delete this favorite then he clicks again and it will run the deleteFavoritesUser method. But my question is what if Favorites is still no created in the database how can i also validate this?.
I runned the app again and I have the same vale created again:
As you can see I have the same automovilesId entry
basically you need to make your favorite button as a toggle button
favoritesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// in place of YES/NO you can take any values to present true/false state
boolean status = v.getTag() != null ? v.getTag().equals("YES") : false;
v.setTag(status ? "NO" : "YES");
if (status) {
// Do favorite me
//AddFavoritesuser();
} else {
// Do un favorite me
//deleteFavoritesUser(key);
}
}
}
everytime i run the android emulator it will create another favorites node.
This is happening because everytime you are trying to add a new object of Favorites class to the database, you are using the push() method, which generates a new random key everytime is called. This is what this method does. So in order to check a property from the database, you need to use in your reference the same key, not to generate another one. Please see in my answer from this post, where I have explained how you can achieve this.

Firebase - how to enumerate all child values' contents?

I'm developing an Android app in Android Studio which lists events based on categories (music, sport, business, theatre). Every event has a name, description, location and time. This is how the events are stored in Firebase when a user posts events through my application:
How can I retrieve e.g. all childs and its contents in the Music category? I have four String arrays to display events (currently manually) like this:
String[] name = {"Eminem","Rihanna"};
String[] desc = {"Concert","Live Show"};
String[] location = {"Miami","Florida"};
String[] time = {"bllablla","bllablla"};
I want to populate the string arrays automatically from firebase, however I'm not sure how to get contents for every child element from Music element? If needed, I can post the Java code which populates the database as well.
Edit: I've tried this:
DatabaseReference info = FirebaseDatabase.getInstance().getReference("Events").child("Music");
info.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot val: dataSnapshot.getChildren()) {
// Retreive all Music childs and then retreive all data of them childs?
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
There is probably no easier solution than to download all of your music data, loop through all children and create corresponding arrays manually -
1) Create a class to map your firebase music record to -
class MusicRecord{
String date;
String eventDescription;
String eventName;
String location;
}
2) Load data, loop through children, retrieve MusicRecords and populate your arrays
protected void loadData(){
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Events").child("Music");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> recordsSnaphots = dataSnapshot.getChildren();
int count = (int) dataSnapshot.getChildrenCount();
int i = 0;
String[] names = new String[count];
String[] descriptions = new String[count];
String[] locations = new String[count];
String[] times = new String[count];
for(DataSnapshot recordSnapshot: recordsSnaphots){
MusicRecord record = recordSnapshot.getValue(MusicRecord.class);
if(record != null) {
names[i] = record.eventName;
descriptions[i] = record.eventDescription;
locations[i] = record.location;
times[i] = record.date;
i++;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
Based on your post, you'll have to do several things :
Create a model
You'll have to create a POJO that describes the structure of the data you have in your Firebase realtime database. In your case, create a class FirebaseEvent that has a Date and three Strings (eventDescription,eventName,location).
Instantiate your class
Based on your last snippet, instantiate your class with the data from your Firebase realtime database. Firebase API is still a bit tedious with this, but this is yet the most common way to do it
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
GenericTypeIndicator<HashMap<String,FirebaseEvent>> ti =
new GenericTypeIndicator<HashMap<String,FirebaseEvent>>() {};
HashMap<String,FirebaseEvent> retrievedEvents = childSnapshot.getValue(ti);
}
Now, what you have is a HashMap with keys like "Eminem" and "Rihanna" and the corresponding value that is a FirebaseEvent.
I choose to use an ArrayList for a dynamic data structure.
I also took a snapshot of my database:
public class MainActivity extends AppCompatActivity {
List<String> name= new ArrayList<String>();
List<String> location= new ArrayList<String>();
List<String> date= new ArrayList<String>();
private DatabaseReference mDatabase;
public static final String TAG= "YOUR-TAG-NAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = FirebaseDatabase.getInstance().getReference().child("Events").child("Music");
// Read from the database
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
for (DataSnapshot values: dataSnapshot.getChildren()) {
//query for the parent of the date "Eminem"
String key = values.getKey().toString();
name.add(key);
//query for location in the music category
date.add(values.child("location").getValue().toString());
//query for date in the music category
date.add(values.child("date").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
}

Firebase won't trigger data change event

I am using Firebase with my Android application. I am trying to use Firebase as a NOSQL database and this is my data retrieval object.
public class FirebaseManager {
private static final String DB_REF = "mainframeradio";
private static final String STREAM_REF = "streams";
public static List<MediaStream> getMediaStreams(Context context) {
final List<MediaStream> mediaStreams = new ArrayList<>();
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference dbRef = db.getReference(STREAM_REF);
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> streams = (Map<String, Object>) dataSnapshot.getValue();
if (!streams.isEmpty()) {
for (Object stream : streams.values()) {
String protocol = (String) ((Map) stream).get("protocol");
String host = (String) ((Map) stream).get("host");
int port = (int) ((Map) stream).get("port");
String media = (String) ((Map) stream).get("media");
String metadata = (String) ((Map) stream).get("metadata");
String streamName = (String) ((Map) stream).get("streamName");
MediaStream mediaStream = new MediaStream(protocol, host, port, media, metadata, streamName);
mediaStreams.add(mediaStream);
}
} else {
L.d("No media streams found on the server.");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
L.w("Couldn't read the stream info from Firebase.");
}
});
return mediaStreams;
}
}
The thing is the event does not get triggered from the activity I am calling it from.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
// Set components.
this.playerView = findViewById(R.id.playerView);
this.songTitleTextView = findViewById(R.id.songTitleTextView);
this.albumArt = findViewById(R.id.albumArt);
// Hide both the navigation and status bar (immersive).
ViewManager.setFullscreenImmersive(getWindow());
List<MediaStream> mediaStreams = FirebaseManager.getMediaStreams(this);
System.out.print(mediaStreams);
}
All I want to do is retrieve the data from firebase. This is the database.
Any help would be appreciated.
Try this to retrieve the data:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("streams");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String hosts=datas.child("host").getValue().toString();
String medias=datas.child("media").getValue().toString();
String metadata=datas.child("metadata").getValue().toString();
String ports=datas.child("port").getValue().toString();
String protocol=datas.child("protocol").getValue().toString();
String steamname=datas.child("streamName").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
the datasnapshot is streams,you then will be able to iterate inside the child 0 and get the data

Categories