Invalid collection reference. Collection references must have an odd number of segments - android

I want to get all documents from a sub-collection.
Here's the path:
Collection(Shops)-Doc(shop)-Collection(year)-Doc(month)-Col(day)-Doc(Current)-Col(initial stocks).
This is how it looks like in firestore:
Numbers - Dhool - 2021 - 10(month) - 06(day) - Begining - initial stock
But I'm getting the following error:
I know there are other questions like that but they are not solving my problems.
Here is the code of the fragment where the query is :
public class DebutFragment extends Fragment {
Calendar calendar;
DatePickerDialog.OnDateSetListener date;
TextView dateView;
String day="", month="", year="";
public DebutFragment() {}
public static DebutFragment newInstance() {
return new DebutFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_actuel, container, false);
dateView = view.findViewById(R.id.date);
this.configureDate();
day = getDay(choosenDate);
month = getMonth(choosenDate);
year = getYear(choosenDate);
this.configureRecyclerView(view);
return view;
}
/////////////
//////////
private void configureDate() {
calendar = Calendar.getInstance();
date = (view, year, month, dayOfMonth) -> {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
};
updateLabel();
dateView.setOnClickListener(v -> new DatePickerDialog(getContext(), date,
calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show());
}
private void updateLabel() {
SimpleDateFormat dateFormatAbreger = new SimpleDateFormat("E dd MMM yy", Locale.FRANCE);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(BIRTHDAY_FORMAT, Locale.FRANCE);
dateView.setText(dateFormatAbreger.format(calendar.getTime()));
choosenDate = simpleDateFormat.format(calendar.getTime());
}
//////////////////
private void configureRecyclerView(View view) {
RecyclerView recyclerView = view.findViewById(R.id.khat_debut_recyclerview);
KhatDebutAdapter adapter = new KhatDebutAdapter(options);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter.notifyDataSetChanged();
}
Query query = getKhatInitialeCollectionReference(day, month, year).orderBy("typ", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<Khat> options = new FirestoreRecyclerOptions.Builder<Khat>()
.setQuery(query, Khat.class).setLifecycleOwner(this).build();
}
Here is the code of all my Firebase methods :
public class FirebaseCalls {
//BOSSES
public static CollectionReference getBossesCollectionReference() {
return FirebaseFirestore.getInstance().collection(PATRONS);
}
public static DocumentReference getBossDocumentReference(String emailBoss) {
return getBossesCollectionReference().document(emailBoss);
}
//NUMBERS
public static CollectionReference getNumbersBigCollectionReference() {
return FirebaseFirestore.getInstance().collection(NUMBERS);
}
public static CollectionReference getNumbersCollectionReference() {
return getBossDocumentReference(currentBoss.getEmail()).collection(NUMBERS);
}
public static DocumentReference getNumberDocumentReference(String name) {
return getNumbersCollectionReference().document(name);
}
public static DocumentReference getNumberBigDocumentReference() {
return getNumbersBigCollectionReference().document(currentNumber.getName());
}
///YEAR
public static CollectionReference getYearCollectionReference(String year) {
return getNumberBigDocumentReference().collection(year);
}
///MONTH
public static DocumentReference getMonthDocumentReference(String month, String year) {
return getYearCollectionReference(year).document(month);
}
public static CollectionReference getDayCollectionReference(String day, String month, String year) {
return getMonthDocumentReference(month, year).collection(day);
}
///COMMENCEMENT
public static DocumentReference getCommencementDocumentReference(String day, String month, String year) {
return getDayCollectionReference(day, month, year).document(COMMENCEMENT);
}
///RESTANT
public static DocumentReference getRestantDocumentReference(String day, String month, String year) {
return getDayCollectionReference(day, month, year).document(RESTANT);
}
Can somebody help me, please?

This issue, as you mentioned, is already pointed out in different questions, and it's related to the Firestore data model. Here you can find detailed information about how this data model is structured. Basically, the error says you can’t have an odd number of segments to refer to a collection; this is because collections are always going to be in an odd position due to how hierarchy structures are designed. The documentation says:
Notice the alternating pattern of collections and documents. Your
collections and documents must always follow this pattern. You cannot
reference a collection in a collection or a document in a document.
You can see the pattern here:
And here is an example used in the documentation implemented in a Chat Application to explain Hierarchy structure:
To understand how hierarchical data structures work in Cloud
Firestore, consider an example chat app with messages and chat rooms.
You can create a collection called “rooms” to store different chat
rooms:
And this is how it’s referenced:
DocumentReference messageRef = db
.collection("rooms").document("roomA")
.collection("messages").document("message1");
This, compared to your application, will be:
Numbers - Dhool - 2021(year) - 10(month) - 06(day) - Beginning -
initial stock
Collection: Numbers
Document: Dhool
Subcollection: 2021(year)
Document: 10(month)
Subcollection: 06(day)
Document: Beginning
Subcollection: Initial Stock
And should be referenced in this way:
CollectionReference NumbersColRef = db.Collection(“Numbers”);
DocumentReference DhoolDocRef = NumbersColRef().Document(“Dhool”);
CollectionReference YearColRef = DhoolDocRef().Collection(“Year”);
DocumentReference MonthDocRef = YearColRef().Document(“Month”);
CollectionReference DayColRef = MonthDocRef().Collection(“Day”);
DocumentReference BeginningDocRef = DayColRef().Document(“Beginning”);
CollectionReference IStockColRef = BeginningDocRef().Collection(“IStock”);
If your structure is already like this, which I can see it is, the error may also occur when the references are not properly called or if one of them is empty or returning an empty or incorrect format value, which might be the case. You can troubleshoot your parameters and see if they are correctly called and also check the entity IDs if they return a type of value format that might cause a problem. The dates may contain a “/” or another symbol that could cause the program to crash, so be sure to parse it to Strings or Integers, or that the values are not being received in a format that could cause this issue. This was found in another forum with the same error, but the cause was a little different from what the error says. Please take in consideration this is not from the official documentation.

Related

Android Room with RxJava: get data from Room with the loop

I am new for using RxJava and Room. What I trying to do is run a for loop to get data from database. The for loop iterate from first day of month to the last day of month.
Here is the Dao for this query.
#Query("SELECT SUM(duration) FROM xxx WHERE timeStamp >= :start and timeStamp <= :end and userId = :userId")
Flowable<Integer> getDuration(String userId, long start, long end);
And Here is how i using RxJava to get the result.
Calendar day1 = Calendar.getInstance();
Calendar day2 = Calendar.getInstance();
int maxLoopIndex = day1.getActualMaximum(Calendar.DAY_OF_MONTH);
day1.setFirstDayOfWeek(Calendar.MONDAY);
day2.setFirstDayOfWeek(Calendar.MONDAY);
day1.set(Calendar.DATE, day1.getActualMinimum(Calendar.DATE));
day2.set(Calendar.DATE, day2.getActualMinimum(Calendar.DATE));
day1.set(Calendar.HOUR_OF_DAY, 0);
day1.set(Calendar.MINUTE, 0);
day1.set(Calendar.SECOND, 0);
day1.set(Calendar.MILLISECOND, 0);
day2.set(Calendar.HOUR_OF_DAY, 23);
day2.set(Calendar.MINUTE, 59);
day2.set(Calendar.SECOND, 59);
day2.set(Calendar.MILLISECOND, 999);
ArrayList<Pair<Long, Long>> maxDayCount = new ArrayList<>();
//Get all the timeStamp in a month, where maxDayCount can be 30, 31, 28, 29.
for (int i = 0; i < maxDayCount; i++) {
Pair<Long, Long> P = Pair.create(day1.getTimeInMillis(), day2.getTimeInMillis());
pairArrayList.add(P);
day1.add(Calendar.DATE, 1);
day2.add(Calendar.DATE, 1);
}
// Using Flowable.formIterable to run through the list and get the data from room
Flowable.fromIterable(pairArrayList)
.flatMap(new Function<Pair<Long, Long>, Flowable<Integer>>() {
#Override
public Flowable<Integer> apply(#NonNull Pair<Long, Long> date) throws Exception {
return roomdb.Dao().getDuration(
User.getCurUser().getId(), date.first, date.second
);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Integer>() {
#Override
public void accept(#NonNull Integer source) throws Exception {
Log.d(TAG, "Duration: "+source);
// I want to get the index of pairArrayList to store the duration in
// corresponding array
}
});
However in subscribe I can get the result return by room however I can not get which index is run in pairArrayList. Is there any way I can get the index? Furthermore is there any better way to get data from room with the loop?
Let's begin with the final structure. It should contain the day of month and duration:
class DayDuration {
public Integer day;
public Long duration;
public DayDuration(Integer day, Long duration) {
this.day = day;
this.duration = duration;
}
#Override
public boolean equals(Object o) { /* implementation */ }
#Override
public int hashCode() { /* implementation */ }
}
Creation of final Flowable what emits requested items might look like the following code. I have used ThreetenBP library to handle date/time operations because Android Calendar API is pure hell. Recommend you do the same:
class SO64870062 {
private Flowable<Long> getDuration(String userId, long start, long end) {
return Flowable.fromCallable(() -> start); // mock data
}
#NotNull
private Flowable<LocalDate> getDaysInMonth(YearMonth yearMonth) { // (1)
LocalDate start = LocalDate.of(yearMonth.getYear(), yearMonth.getMonthValue(), 1);
LocalDate end = start.with(TemporalAdjusters.lastDayOfMonth());
return Flowable.create(emitter -> {
LocalDate current = start;
while (!current.isAfter(end)) { // (2)
emitter.onNext(current);
current = current.plusDays(1);
}
emitter.onComplete();
}, BackpressureStrategy.BUFFER);
}
#NotNull
private Flowable<DayDuration> getDurationForDay(String userId, LocalDate localDate) {
long startDayMillis = localDate.atStartOfDay().atZone(ZoneOffset.UTC) // (3)
.toInstant()
.toEpochMilli();
long endDayMillis = localDate.atTime(LocalTime.MAX).atZone(ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
return getDuration(userId, startDayMillis, endDayMillis) // (4)
.map(duration -> new DayDuration(localDate.getDayOfMonth(), duration));
}
public Flowable<DayDuration> getDayDurations(String userId, YearMonth yearMonth) {
return getDaysInMonth(yearMonth)
.flatMap(localDate -> getDurationForDay(userId, localDate));
}
}
Important and interesting parts:
Function getDaysInMonth() creates Flowable what emits all days of requested month.
Iteration from start (first day of a month) to end (last day of a month) date and emitting all of the days.
Make sure you set the zone you use within timestamps in your database. I have used UTC for simplicity.
Combine duration from a database with the current date.
Last but not least, let's check if it works correctly:
public class SO64870062Test {
#Test
public void whenDaysRequestedForApril2020ThenEmitted() {
SO64870062 tested = new SO64870062();
TestSubscriber<DayDuration> testSubscriber = tested
.getDayDurations("userId", YearMonth.of(2020, 11))
.test();
testSubscriber.assertValueCount(30);
testSubscriber.assertValueAt(1, new DayDuration(2, 1604275200000L));
testSubscriber.assertComplete();
}
}

RxJava2 emit items in order

I'm making a exchange rate app and I have a screen with a graph that shows changes of the selected currency in the last 7 days.
Now what I wanna get is to emit items in strict order.
Here is my code:
public class GraphInteractorImpl implements GraphInteractor {
private final Retrofit retrofit;
#Inject
public GraphInteractorImpl(Retrofit retrofit) {
this.retrofit = retrofit;
}
#Override
public void downloadData(GraphListener listener) {
RestAPI api = retrofit.create(RestAPI.class);
List<String> listDates = getDates();
for (String date : listDates) {
Observable<List<ExchangeRate>> observable = api.getExchangeRatesForLast7days(date);
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
listener::onSuccess,
listener::onFailure
);
}
}
private List<String> getDates() { //returns last 7 days in a list
List<String> listDate = new ArrayList<>();
Calendar calendarToday = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String today = simpleDateFormat.format(calendarToday.getTime());
Calendar calendarDayBefore = Calendar.getInstance();
calendarDayBefore.setTime(calendarDayBefore.getTime());
int daysCounter = 0;
while (daysCounter <= 7) {
if (daysCounter == 0) { // means that its present day
listDate.add(today);
} else { // subtracts 1 day after each pass
calendarDayBefore.add(Calendar.DAY_OF_MONTH, -1);
Date dateMinusOneDay = calendarDayBefore.getTime();
String oneDayAgo = simpleDateFormat.format(dateMinusOneDay);
listDate.add(oneDayAgo);
}
daysCounter++;
}
return listDate;
}
}
This code gets me the right values but they are not in order so I'm getting wrong values for specific days.
So what I have to do is execute 7 calls simultaneously, I'm guessing with zip operator but I didnt come up with a solution for this yet so any type of help would be appreciated.
API docs can be found here: http://hnbex.eu/api/v1/
So what I did to solve this is I added all the 7 observables in a list and then I just called the zipIterable() on that list

Common time for Firebase Database

I am creating a chatting application for android. I am using Firebase Real time database for this purpose. This is how "chats" branch of database looks like :
There are unique ID's for chat rooms generated using Users unique ID's such as "513","675" etc. Inside theese chatrooms there are message objects which also have unique ID's and inside them they store information of the date message sent, name of the sender, and the text of the message. Constructor of Message object is as follows :
public Message(String text,String senderUID, Long date){
this.text = text;
this.senderUID = senderUID;
this.date = date;
}
This is how I generate Time for the each message and send them to firebase database.
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calendar = Calendar.getInstance();
String second,hour,minute;
String time;
if(calendar.get(Calendar.SECOND)<10){
second = "0"+calendar.get(Calendar.SECOND);
}
else
{
second = ""+calendar.get(Calendar.SECOND);
}
if(calendar.get(Calendar.MINUTE)<10){
minute = "0"+calendar.get(Calendar.MINUTE);
}
else
{
minute = ""+calendar.get(Calendar.MINUTE);
}
if(calendar.get(Calendar.HOUR)<10){
hour = "0"+calendar.get(Calendar.HOUR);
}
else
{
hour = ""+calendar.get(Calendar.HOUR);
}
time = date + hour + minute + second;
Log.d("time",time);
Message message = new Message(messageEditText.getText().toString(), user.getDisplayName(), Long.valueOf(time));
chatRoomDatabaseRef.child(chatID).child(user.getUid() + generateRandomNumber()).setValue(message);
messageEditText.setText("");
}
});
Here is how I get the data from database with value event listener :
chatRoomDatabaseRef.child(chatID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<Message> set = new HashSet<Message>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Message message = snapshot.getValue(Message.class);
set.add(message);
}
messageList.clear();
messageList.addAll(set);
Collections.sort(messageList, new Comparator<Message>() {
#Override
public int compare(Message o1, Message o2) {
return Long.valueOf(o1.date).compareTo(Long.valueOf(o2.date));
}
});
messageAdapter.notifyDataSetChanged();
messageListView.setSelection(messageAdapter.getCount() - 1);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
After I get the data from Firebase database I order them according to their date attribute and list them. Everything works fine but when I am filling messages' date attribute, it fills according to the local time on the phone because of that I can't sort the messages correctly. Time can differ device to device. I need to use a Time which is common and same for all the devices using my app. But I couldn't find a way.
Edit:
I still couldn't figure out but as a quick solution I created an object called sequence number in the database. I added one more attribute to the message constructor called sequence number. I read the sequence number from the database, give that number to the next message and increase the value in the database for the new messages. Then I order messages according to that number. It is not the best way to do that but it is something until I find a better way.
Try this
firebase
.database()
.ref("/.info/serverTimeOffset")
.on("value", function(offset) {
let offsetVal = offset.val() || 0;
let serverTime = Date.now() + offsetVal;
console.log("serverTime", serverTime);
});
Use as time
Message message = new Message(messageEditText.getText().toString(), user.getDisplayName(), ServerValue.TIMESTAMP);
and for retrieving it
private String getDate(long time) {
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy", cal).toString();
return date;
}

Firebase ServerValue.TIMESTAMP in Java data models objects

I'm new to Firebase, and I've been really enjoying it so far. I'm running into a problem; I'm using the FirebaseListAdapter similar to the tutorial outline here: https://github.com/firebase/AndroidChat
To use the FirebaseListAdapter, I need to use data model objects (to get the automatic binding to work nicely). The problem is I also want to keep a timestamp value with that model object, and I want to get the timestamp from the Firebase server.
What I have currently that is NOT working is a class DataModelObject (similar to com.firebase.androidchat.Chat in the demo example) with a constructor like :
DataModelObject(String data1, String data2, Map enQTimeStamp)
which I then try to use like this:
DataModelObject dmo = new DataModelObject ("foo", "bar", ServerValue.TIMESTAMP);
myFirebaseRef.push().setValue(dmo);
This causes a JsonMappingException when I try to run that code. I found a code snippet here :
https://www.firebase.com/blog/2015-02-11-firebase-unique-identifiers.html
But it's worthwhile to note that on line 4 of the Android code example, that will cause a compile time error (as he is trying to put ServerValue.TIMESTAMP into a Map, and TIMESTAMP is a Map itself)
What is the right way to do this and maintain compatibility with FirebaseListAdapter?
This sounds similar to this question: When making a POJO in Firebase, can you use ServerValue.TIMESTAMP?
When creating POJOs used to store/retrieve data apart from the default empty constructor I usually use a constructor similar to this:
Param param1;
Param param2;
HashMap<String, Object> timestampCreated;
//required empty constructor
public DataObject(){}
public DataObject(Param param1, Param param2) {
this.param1 = param1;
this.param2 = param2;
HashMap<String, Object> timestampNow = new HashMap<>();
timestampNow.put("timestamp", ServerValue.TIMESTAMP);
this.timestampCreated = timestampNow;
}
Be sure to include a getter for the HashMap<> used to store the Timestamp:
public HashMap<String, Object> getTimestampCreated(){
return timestampCreated;
}
Then use the #Exclude annotation to create a getter that you can use in your code to get the value of the timestamp if you need it. The #Exclude annotation will cause Firebase to ignore this getter and not look for a corresponding property
#Exclude
public long getTimestampCreatedLong(){
return (long)timestampCreated.get("timestamp");
}
Here's how I do it
//member variable
Object createdTimestamp;
public YourConstructor(){
createdTimestamp = ServerValue.TIMESTAMP
}
#Exclude
public long getCreatedTimestampLong(){
return (long)createdTimestamp;
}
Your db object should include these:
public class FirebaseDbObject {
private final Object timestamp = ServerValue.TIMESTAMP;
//........
//........
Object getTimestamp() {
return timestamp;
}
#Exclude
public long timestamp() {
return (long) timestamp;
}
}
This will add an extra field called "timestamp" to your object.
Edit: The answer posted by MobileMon is not fully correct as it does not have getter method. This is the complete and correct answer.
Kotlin provides an easy way to achieve this by data classes. You can create it like
data class FirebaseRequestModel(
var start_time: Any = ServerValue.TIMESTAMP,
var stop_time: Long = 0,
var total_time: Long = 0,
)
and use it directly by
val firebaseModel = FirebaseRequestModel()
firebaseRef.setValue(firebaseModel)
This will get default values from data class.
Or even you can initiate your own values by
val firebaseModel = FirebaseRequestModel(ServerValue.TIMESTAMP, 2134, 0)
firebaseRef.setValue(firebaseModel)
Similar to Urgurcan's answer, but a bit cleaner so the caller doesn't have trouble guessing between getTimestamp vs timestamp.
public class FirebaseDbObject {
private Object timestamp = ServerValue.TIMESTAMP;
//........
//........
#PropertyName("timestamp")
Object getRawTimestamp() {
return timestamp;
}
#Exclude
public long getTimestamp() {
return (long) timestamp;
}
}
You can do it:
public class MyTimeStamp {
private Object timestamp;
public MyTimeStamp() {
}
public Object getTimestamp() {
return timestamp;
}
public void setTimestamp(Object timestamp) {
this.timestamp = timestamp;
}
}
And so:
public static void start(Context context) {
MyTimeStamp timeStamp = new MyTimeStamp();
timeStamp.setTimestamp(ServerValue.TIMESTAMP);
Log.d(TAG, "start: ", timeStamp.getTimestamp().toString());
}

Removing element from ArrayList<HashMap<String, String>>

Hi I have this array list of hashmaps
[{EndTime=09:00 AM, UserId=48, StartTime=08:00 AM, AppointmentId=79, Date=11/18/13},
{EndTime=09:00 AM, UserId=48, StartTime=08:00 AM, AppointmentId=80, Date=11/18/13},
{EndTime=09:00 AM, UserId=48, StartTime=08:00 AM, AppointmentId=81, Date=11/18/13},
{EndTime=09:00 AM, UserId=48, StartTime=08:00 AM, AppointmentId=82, Date=11/18/13},
{EndTime=09:00 AM, UserId=48, StartTime=08:00 AM, AppointmentId=83, Date=11/18/13},
{EndTime=09:00 AM, UserId=48, StartTime=08:00 AM, AppointmentId=85, Date=11/18/13}]
I want to check particular entry from here using "AppoinmentID" and i want to get that record for a diferent hashmap and all the others to a different one.. how can I do it? Thanks in advance.
storing these values in a hashmap is not a good idea. why don't you create an appointment class. removing an appointment object will be easy in this case.
public class Appointment
{
private int appointmentId;
private int userId; // or private User user
private Date start;
private Date end;
public Appointment(int id)
{
this.appointmentId = id;
}
// getters and setters
#Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (this.getClass() != obj.getClass())
{
return false;
}
Appointment other = (Appointment) obj;
if (this.appointmentId != other.appointmentId)
{
return false;
}
return true;
}
}
now if you want to delete a specific item with a certain ID:
List<Appointment> appointments = new ArrayList<Appointment>();
appointments.remove(new Appointment(theIdYouWantToDelete));
or an even better way:
Store them like this
Map<Integer, Appointment> appointments = new HashMap<Integer, Appointment>();
appointments.put(appointment.getAppointmentId(), appointment);
and remove them like this:
appointments.remove(theIdYouWantToDelete);
with this approach, you do not need the equals method.
Why it works:
When you want to remove an Object from a List or a Map, Java uses the equals method to identify them. As You can see i only check for the appointmentId. So if the IDs of 2 object are the same, Java says they are the same object. If you don't override equals, check only checks for == (same object in the memory) which mostly isn't the case.
1.Create a class
public class Appointment
{
public int appointmentId;
public int userId;
public Date startTime;
public Date endTime;
public Appointment(int id,int aUserID,Date aStartTime,Date aEndTime)
{
this.appointmentId = id;
this.userId = aUserID;
this.startTime = aStartTime;
thiis.endTime = aEndTime;
}
}
2. Creating Appointment Object and Storing in HashMap
String dateFormat = "MMMM d, yyyy HH:mm"; //any date format
DateFormat df = new SimpleDateFormat(dateFormat);
Date startDate = df.parse("January 2, 2010 13:00");
Date endDate = df.parse("January 2, 2010 20:00");
Appointment appointment1 = new Appointment(1,23,startDate,endDate);
...
Map<Integer, Appointment> appointments = new HashMap<Integer, Appointment>();
// add to hashmap making appointment id as key
appointments.put(appointment1.appointmentId,appointment1);
......
...
appointments.put(appointmentN.appointmentId,appointmentN);
3. deleting an Appointment Object
appointments.remove(aAppointmentId)
4. getting an Appointment Object
Appointment ap = appointments.get(aAppointmentId);
System.out.printLn("id "+ ap.appointmentId);
System.out.printLn("userId "+ ap.userId);
DateFormat df = new SimpleDateFormat(dateFormat);
System.out.printLn("starttime "+ df.format(ap.startTime));
System.out.printLn("endtime "+ df.format(ap.endTime));
You can have class:
public class Apointment{
Stirng EndTime="09:00 AM";
int AppointmentId=79;
...
...
}
and have one hashmap with apointmentId as key
HashMap<Integer,Apointment> map=new HashMap<Integer,Apointment>();
Apointment ap=new Apointment(...);
map.put(ap.getAppointmentId(),ap);
..
..
..
And if you have apointmentID you can get apointment object by:
Apointment ap=map.get(79);

Categories

Resources