I have firebase database in my android project which contains three values: code, email, date. I am using switchcompat for counting present students in the firebase database. When switch will be checked, data will enter into the firebase database checking if the email is uniqe in the specific date. When switch will be unchecked, that current date's data will be removed. But my problem is that for the first time when I check the switch, it works fine. And in the second time after unchecking the switch once, when I check it once again, it enters data into firebase but also remove it automatically immediately even switch is still checked. I don't understand where is the problem in my code.
I am providing my code in the below for working of SwitchCompat.
Here is the code:
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
final String date = df.format(c);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
final String previousDate = df.format(cal.getTime());
final int[] i = {0};
if (switch1.isChecked()) {
Query equery = present.orderByChild("email").equalTo(email);
equery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
String code = "1";
PresentStu presentStu = new PresentStu(FirebaseAuth.getInstance().getCurrentUser().getEmail(), date, code);
String uploadId = present.push().getKey();
present.child(uploadId).setValue(presentStu);
} else {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String eemail = snapshot.child("email").getValue().toString();
String ddate = snapshot.child("date").getValue().toString();
if (eemail.equals(eemail) && ddate.equals(date)) {
i[0]++;
break;
}
}
// Toast.makeText(User.this,""+i[0]+"",Toast.LENGTH_SHORT).show();
if (i[0] < 1){
String code = "1";
PresentStu presentStu = new PresentStu(FirebaseAuth.getInstance().getCurrentUser().getEmail(), date, code);
String uploadId = present.push().getKey();
present.child(uploadId).setValue(presentStu);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
} else {
Query equery = present.orderByChild("email").equalTo(email);
equery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String eemail = snapshot.child("email").getValue().toString();
String ddate = snapshot.child("date").getValue().toString();
if (eemail.equals(eemail) && ddate.equals(previousDate)) {
present.child(dataSnapshot.getChildren().iterator().next().getKey()).child("code").setValue("0");
}
if (eemail.equals(eemail) && ddate.equals(date)) {
snapshot.getRef().removeValue();
break;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
});
Please, help me to find out the lacking in my code.
My database structure
Because I do not know the structure of you database, you can't simply copy/paste this snippet; it is your own code with the event listeners removed.
Get the right path to your snapshot with the right and make the change directly, without waiting for a data change.
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
final String date = df.format(c);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
final String previousDate = df.format(cal.getTime());
final int[] i = {0};
if (switch1.isChecked()) {
Query equery = present.orderByChild("email").equalTo(email);
// TODO Change this:
DataSnapshot dataSnapshot = equery.doSomethingToGettheSnapshot()
if (!dataSnapshot.exists()) {
String code = "1";
PresentStu presentStu = new PresentStu(FirebaseAuth.getInstance().getCurrentUser().getEmail(), date, code);
String uploadId = present.push().getKey();
present.child(uploadId).setValue(presentStu);
} else {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String eemail = snapshot.child("email").getValue().toString();
String ddate = snapshot.child("date").getValue().toString();
if (eemail.equals(eemail) && ddate.equals(date)) {
i[0]++;
break;
}
}
// Toast.makeText(User.this,""+i[0]+"",Toast.LENGTH_SHORT).show();
if (i[0] < 1){
String code = "1";
PresentStu presentStu = new PresentStu(FirebaseAuth.getInstance().getCurrentUser().getEmail(), date, code);
String uploadId = present.push().getKey();
present.child(uploadId).setValue(presentStu);
}
}
}
} else {
Query equery = present.orderByChild("email").equalTo(email);
// TODO Change this:
DataSnapshot dataSnapshot = equery.doSomethingToGettheSnapshot()
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String eemail = snapshot.child("email").getValue().toString();
String ddate = snapshot.child("date").getValue().toString();
if (eemail.equals(eemail) && ddate.equals(previousDate)) {
present.child(dataSnapshot.getChildren().iterator().next().getKey()).child("code").setValue("0");
}
if (eemail.equals(eemail) && ddate.equals(date)) {
snapshot.getRef().removeValue();
break;
}
}
}
}
}
});
Related
I'm using GraphView library. My code below gets data from Firebase real-time database and updates the graph with values from database, but it isn't sorted. I need it to be sorted in ascending order in X axis. The data in X axis is Long type, then it's converted to date.
I've tried adding dp[index] to array list and using different sorting methods, but nothing seems to work.
#Override
public void onStart() {
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
FirebaseAuth auth;
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
String id = user.getUid();
DataPoint[] dp = new DataPoint[(int) snapshot.child(id).getChildrenCount()];
int index = 0;
for(DataSnapshot myDataSnapshot : snapshot.child(id).getChildren()){
PointValue pointValue = myDataSnapshot.getValue(PointValue.class);
dp[index] = new DataPoint(pointValue.getxValue(), pointValue.getyValue());
index ++;
}
lineGraphSeries.resetData(dp);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
super.onStart();
}
AlertDialog, where data is being written to the database:
builder.setPositiveButton("ADD",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(TextUtils.isEmpty(weightEditText.getText().toString()) || TextUtils
.isEmpty(dateEditText.getText().toString())) {
Toast.makeText(getActivity(),"Please provide weight and date",
Toast.LENGTH_SHORT).show();
} else{
linearLayout.addView(createNewTextView(weightEditText.getText().toString(),
dateEditText.getText().toString()));
String id = user.getUid();
String randomId = reference.push().getKey();
try {
Date date = sdf.parse(dateEditText.getText().toString());
long x = date.getTime();
int y = Integer.parseInt(weightEditText.getText().toString());
PointValue pointValue = new PointValue(x,y);
reference.child(id).child(randomId).setValue(pointValue);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
});
builder.setView(view);
builder.show();
PointValue class:
public class PointValue {
long xValue;
int yValue;
public PointValue() {
}
public PointValue(long xValue, int yValue) {
this.xValue = xValue;
this.yValue = yValue;
}
public long getxValue() {
return xValue;
}
public int getyValue() {
return yValue;
}
}
#EDIT
Thanks to #Frank van Puffelen, I've managed to sort my data from Firebase Database using orderByChild()
https://firebase.google.com/docs/database/android/lists-of-data#sort_data
below working solution:
#Override
public void onStart() {
FirebaseAuth auth;
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
String id = user.getUid();
Query dateAscendingOrder = database.getReference("users")
.child(id).orderByChild("xValue");
dateAscendingOrder.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
DataPoint[] dp = new DataPoint[(int) snapshot.getChildrenCount()];
int index = 0;
for (DataSnapshot myDataSnapshot : snapshot.getChildren()){
PointValue pointValue = myDataSnapshot.getValue(PointValue.class);
dp[index] = new DataPoint(pointValue.getxValue(), pointValue.getyValue());
index++;
}
lineGraphSeries.resetData(dp);
}
I am trying to add events dynamically from Firebase , but I'm not able to display any events, I am using Alamkanak Week-View , I stuck with problem and try many ways because onMonthChange called before executing firebase, please help guys.
private void RetriveAllAppointment(ArrayList<String> id_list) {
mrefDatabase = FirebaseDatabase.getInstance().getReference("Appointments").child("Active");
mrefDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
times_list = new ArrayList<>();
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
appointmantdate = snapshot.child("Date").getValue().toString();
selectedVenueName = snapshot.child("venueName").getValue().toString();
if (snapshot.hasChild("times")) {
for (DataSnapshot timesnapshot
:snapshot.child("times").getChildren()) {
String time = timesnapshot.getValue().toString();
times_list.add(time);}
CreateEvent(year, month);}
create event from data that come from firebase
public void CreateEvent(int year, int month) {
String[] separated = appointmantdate.split("-");
int year_ = Integer.parseInt(separated[0]);
int month_ = Integer.parseInt(separated[1]);
int day = Integer.parseInt(separated[2]);
for (int a = 0; a < times_list.size(); a++) {
String[] timeSplit = times_list.get(a).split(":");
int time_hour = Integer.parseInt(timeSplit[0]);
int time_minute = Integer.parseInt(timeSplit[1]);
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, time_hour);
startTime.set(Calendar.MINUTE, time_minute);
startTime.set(Calendar.DAY_OF_MONTH, day);
startTime.set(Calendar.MONTH, month_ - 1);
startTime.set(Calendar.YEAR, year_);
Calendar endTime = (Calendar) startTime.clone();
String[] endtimeSplit = times_list.get(times_list.size() - 1).split(":");
int endtime_hour = Integer.parseInt(endtimeSplit[0]);
int endtime_minute = Integer.parseInt(endtimeSplit[1]);
endTime.add(Calendar.HOUR, endtime_hour);
startTime.set(Calendar.MINUTE, endtime_minute);
endTime.set(Calendar.MONTH, month - 1);
event = new WeekViewEvent(1, selectedVenueName, startTime, endTime);
event.setColor(getActivity(). getResources().getColor(R.color.event_color_03));
events.add(event);}
onMonthChange method
#Override
public List<? extends WeekViewEvent> onMonthChange(int newYear, int newMonth) {
List<WeekViewEvent> lastone = new ArrayList<WeekViewEvent>();
if (appointmantdate != null && times_list != null) {
lastone = CreateEvent(newYear, newMonth);
events.addAll(lastone);
}
ArrayList<WeekViewEvent> matchedEvents = new ArrayList<WeekViewEvent>();
for (WeekViewEvent event : events) {
if (eventMatches(event, newYear, newMonth)) {
matchedEvents.add(event);
}
return matchedEvents;
I have this button that will generate time and date and set it as a child in a database tree, the problem is whenever I click buttons it generates the said time but the time is not changing,
for example i clicked on the button and it generates the time 12:27 Pm, and it will be recorded into the database, now i clicked the button again for the second time and it doesn't change still printing out the 12:27 Pm Instead 12:30 Pm.
the code looks like this
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer num1 = Integer.parseInt(edt1.getText().toString());
Integer num2 = Integer.parseInt(edt2.getText().toString());
Integer result = num1+num2;
String data = "Date Computed: " + Date + Hrs +"Result: "+ result;
DateView.setText(data);
HashMap<String, String> userMap = new HashMap<>();
userMap.put("Add", data);
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("Users").child("UserID").child(Date);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
maxid = (snapshot.getChildrenCount());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
reference.child("Transaction"+maxid).setValue(userMap);
}
});
edt1 = findViewById(R.id.edt1);
edt2 = findViewById(R.id.edt2);
btnadd = findViewById(R.id.btnadd);
btnmin = findViewById(R.id.btnmin);
DateView = findViewById(R.id.DateView);
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date = simpleDateFormat.format(calendar.getTime());
simpleHoursFormat = new SimpleDateFormat(" hh:mm:ss ");
Hrs = simpleHoursFormat.format(calendar.getTime());
Hi from the code it looks like you haven't updated your Date and Time in your onClickListener. The updated code should be like this :-
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// This will fetch your updated date and time
Date = simpleDateFormat.format(calendar.getTime());
Hrs = simpleHoursFormat.format(calendar.getTime());
Integer num1 = Integer.parseInt(edt1.getText().toString());
// Rest of your code
Try to use this
import java.util.Calendar
Date currentTime = Calendar.getInstance().getTime();
Hye, my problem is to rewrite if the user put the same nameItem that will change the price and the quantityItem, if not the item will add new id. i also do auto increment on id.
My Database :
This is how i try but when the name == nameItem can't read and run on else in on DataChange.
if(i != 0){
for(id1 = 1; id1<=i; id1++){
if(id1 != 0){
final DatabaseReference reff1 = FirebaseDatabase.getInstance().getReference().child("CartList").child(userID).child(String.valueOf(id1));
reff1.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String carinama = dataSnapshot.child("nameItem").getValue().toString();
String changequantity = dataSnapshot.child("quantityItem").getValue().toString();
if(nameItem == carinama) {
int calcQuantity = Integer.parseInt(cdtb.getQuantityItem());
newpositionItem = newpositionItem + calcQuantity;
String x = String.valueOf(newpositionItem);
cdtb.setQuantityItem(x);
int price1Item = Integer.parseInt(priceItem);
newpositionItem = newpositionItem * price1Item;
cdtb.setPriceItem(d2f.format(newpositionItem));
reff1.setValue(cdtb);
id1 = i;
}else {
int calcQuantity = Integer.parseInt(changequantity);
newpositionItem = newpositionItem + calcQuantity;
String x = String.valueOf(newpositionItem);
cdtb.setQuantityItem(x);
double price1Item = Double.parseDouble(priceItem);
newpositionItem = newpositionItem * price1Item;
cdtb.setPriceItem(d2f.format(newpositionItem));
reff1.setValue(cdtb);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getContext(), ""+databaseError, Toast.LENGTH_SHORT).show();
}
});
}else {
}
}
}else{
cdtb.setImageItem(imageUrl);
cdtb.setNameItem(nameItem);
cdtb.setPriceItem(d2f.format(calcPrice));
cdtb.setSpecification(specItem);
cdtb.setQuantityItem(positionItem);
reff.child(String.valueOf(++maxid)).setValue(cdtb);
}
Thank you...
nameItem and carinama is String
in java to compare two string you must use equals method not "=="
because == will compare object location in memory and not the content string
so you code condition will be
if(nameItem.equals(carinama)){
//your code here
}
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