Adding Data separately to all objects in an arraylist - java

I'm stuck at the moment on a problem, I'm trying to add data separately to all objects in an array list.
eg. Daily, I want to be able to add how much medication each patient has taken to their record in the arraylist.
Each patient has a unique identifier which is whats in the arraylist.
I was wondering using JOptionPane is it possible to pull up each patient separately, so that after one is entered the next shows up to enter in information and how would I go about doing it?
Thanks!

Pseduo code of the data structure might be as following :
class Patient{
String patientId;
List<Medication> list;
public addMedication(Medication med){
list.add(med);
}
}
class Medication{
String name;
...
}
class PatientManager{
Map<String,Patient> map;
public addMedication(String patientId,Medication med){
map.get(patientId).addMedication(med);
}
}

Related

Constructing object

I have a query in constructing an object and storing it in database in json format.
Its in air domain industry. Need to construct an ojbect and store it in database in json format so the other applications can use the same object for various test automation scripts.
What i have done is i have created a class called PassengerDetails and inserted to station, from station etc., as below.
class PassengerDetails{
private String toStation;// Origin
private String fromStation;// destination
private String noOfAdults;
and getters and setters.
}
The passenger type also changes, like infants, companions etc., and i am not understanding how to handle it in class PassengerDetails. I have a guess like i have to add another class for PassengerType. Please correct me if i am wrong and suggest me how to add that passengertype details.
And I have created one ticket class (one ticket for each passenger, if 3 adults are there then 3 tickets and and three tickets are associated with one unique PNR). Here we have to store how the ticket is purchased, i mean by cash or credit card
class PaymentDetails{
private String creditCardType;
private String creditCardNo;
private String creditCardHolderName;
private String cash;
getters and setters.
}
We are having different payment types like Creditcard, cash, vouchers, refund amount etc., I am in confusion again how to handle this in the above PaymentDetails Class and how to link this class with TicketInformation and PassengerDetails
class TicketInformation{
private List<PassengerDetails> passengerDetails;
Getters and setters...
}
For multiple tickets, we have one PNR.
class PNRDetails{
List<TicketInformation> ticketInformationList = new ArrayList();
getters and setters.
}
Now i have a query like, if there is modification in flights or dates etc., new ticket will be issued. Now the question is how to store this new tickets and old tickets so that the user who retrieves the list of tickets can understand that there is a modification and hence there are new tickets and old tickets.
The other scenario is that if there is an addition of additonal passenger then not only the ticket changes but also the PNR changes, Now the question is i want to store both new and old PNRs and associated tickets.
For multiple PNR's how to write the class, do i have to write a class where it has List as instance variable. I messed up the code and i am in confusion. Could any one suggest better approach in modifications of code.
Here's an example on how to create an object and storing in json format:
var myObj = { "name":"John", "age":31, "city":"New York" };
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
This is a very simple example of course.
Go through this website for more information and tutorials:
https://www.w3schools.com/js/js_json_intro.asp

Storing and comparing against objects from a database

I am working on an android app that loads in a list of students to display in a list based activity. There are two components to the app. There is a server which responds via xml with the list of current active students and a database on the app end which stores theses students with some details (name,age etc). I would like a way to sync these two data sources. When the app starts, I would like to check against the xml to see if students on the server were added/deleted and update the db accordingly.
I would be parsing the xml list into a student object at login. Is there any way to store/retrieve an entire object into an android supported db so I can do a direct comparison to see what to update/delete? It would end up being something like
if (serverStudent[0].name == dbStudent[0].name)
//overwrite dbStudent object with serverStudent fields
What is the most efficient/lightweight way to achieve object persistance and then comparison in Android?
Here's a method I have used in the past:
Anytime an object in the database is changed, use a timestamp column to store that time. When the app connects on startup, simply check each timestamp in the app db against the timestamp in the server db for each object. If the timestamps match, do nothing. If the timestamps don't match, retrieve the updated record from the server. Make sure you're using a detail enough timestamp (usually down to milli- or micro- seconds).
The nice thing about timestamps is that if you don't want the server data to override the app data, you could look at which is newer and keep that object if they've both been edited. Just adding some additional thoughts!
You can do something like this -
public class StudentRecord {
Vector<StudentData> studentDatas;
public StudentRecord()
{
studentDatas = new Vector<StudentData>();
}
public Vector<StudentData> getRecords() {
return studentDatas;
}
public void setRecords(Vector<StudentData> records) {
this.studentDatas = records;
}
public class StudentData
{
String name,Rollno;
public String getRollno() {
return Rollno;
}
public void setRollno(String rollno) {
Rollno = rollno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
When you get the vector object studentDatas you can do something like this -
for(Object object : record.getRecords())
{
data = (StudentData)object;
data.getRollno();
data.getName();
}
Check out these libraries:
http://www.datadroidlib.com/
https://github.com/octo-online/robospice
I believe both offer solutions for your situation.
Or you can roll your own solution... Basically you will want to create a service or asynctask to do the syncing, in your student object you can create a constructor that you can pass an id to and have it pull the appropriate record from your local db then make a comparison method that will update if newer information is available.
I'm not sure i understood your question correctly.But as far as i understand i would do something like this.
In server side send send Json array which holds json student objects.
In android side create similer Student class and override equals
method as you want.
Then for each student check with equals method whether they are
equals or not and take action accordingly.
If you want to make faster search in students object array then apply
hash map instead of arrays.

Keeping track of scores in Java

I'm new to Java and I'm currently writing a program for an assignment that represents a 'sports league' (classes to represent player/club/match/league)
My main problems are occurring in the league class. Here are the relevant variables to give you an idea how I'm storing things:
public class League
{
private String leagueName;
private ArrayList<Club> clubs;
private ArrayList<Match> fixtures;
private ArrayList<String> results2;
private TreeMap<Match, String> results;
private String topTeam;
private String goldenBoot;
}
Currently trying to write a method in the League class which will print a 'league table' - i.e. a list of Clubs sorted by their points tally (held as variable in Club class) and I'm drawing a blank on it.
Further to this, I need to write two methods to find the top scorer (golden boot) and find the top team in the league; again I am drawing a blank. Perhaps I am overcomplicating things?
Would be very grateful for suggestions/sample methods
EDIT:
Ok, so that method I'm trying to write is something beginning with:
public void getLeagueTable() {
for(Club c : clubs) {
c.getTally();
}
}
which would give the tally value for each Club object - but how to sort these results, and how to associate the highest with one Club is what's really troubling.
To print the league table, you are going to need to sort the club array and then loop through each item and print the club name.
To sort the club array try using Collections.sort http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html
.. that is assuming you havent been told to implement your own algorithm
Again, more sorting required to get the top team and top scorer, then you will need to pick the top item from the sorted list.
Hope that helps...
You better use Set rather than ArrayList. And here is a good start for your question :
void printLeagueTable(){
i = 0 ;
while( i != clubs.size() ){
Club club = clubs.get(i);
System.out.println("club: "+i+ "points: " club.points() );
}
}

how to perform joins in java without database

I need to perform Joins on 2 tables (that I have read from 2 CSV files) without use of database. I have no idea on collections (List, ArrayList). If anyone can give a detail piece of sample code on any one type of join that would be helpful.
For example I have 2 lists :
a=[2,3,4]
b=[3,4,5]
If it is an inner join
output: [3,4]
Tried so far:
for i in a:
for j in i:
if (i==j):
print(i)
Assuming that you have the following CSV files:
id,name,description
1,Foo,FooBar
2,Bar,BarFo
3,Hey,Ho
and the second one:
id,year
2,1990
1,1923
Then you could have the following structures (I'm skipping the constructors and methods for now):
public class Item {
public String name;
public String description;
}
and the second:
public class Date {
public final int year;
}
Then you could have a third one:
public class Joined {
public final Item item;
public final Date date;
}
And then you could have a Map<Integer,Joined>, and you can read the first CSV and create the Joined objects with only the Item part filled out, then read the second CSV and you could fill up the Date part of the Joined object.
In this joining part, you can decide which joining type you want to implement.
If you have a different key, then you have to change the key of the Map, or you may need to create a new class if you have a complex key.

Problems merging multiple objects into a complex object for Morphia

I'm trying to merge these three objects into a single complex object:
public class Person {
private String name;
private List<Event> events;
// getters and setters
}
public class Event {
private String name;
private List<Gift> gifts;
// getters and setters
}
public class Gift {
private String name;
private String recipient;// the name of the person
private String eventName;
// getters and setters
}
My goal is to save the Person object in MongoDB using Morphia and this how I want my document laid out. I've created a document builder, of sorts, that combines lists of each object. Each Person gets a list of all Events, but can only receive specific Gifts. While my document builder does create a document that Morphia can persist, only the Gifts of that last recipient (sort order) are inserted into the Events for all Persons. Though for the correct Events.
public void merge() {
for (Person person : listOfPersons) {
for (Event event : listOfEvents) {
// somePersonsGifts: a sublist of gifts based on Event and Person.
List<Gift> somePersonsGifts = new ArrayList<Gift>();
for (Gift gift : listOfGifts) {
if (person.getName().equals(gift.getRecipient()) && gift.getEventName().equals(event.getName())) {
somePersonsGifts.add(gift);
}
}
event.setGifts(somePersonsGifts);
}
person.setEvents(listOfEvents)
}
}
If I modify the code slightly to process one person at a time by removing the outer loop and having the method take an argument for specific index of the Persons list:
public void merge(int p) {
Person person = listOfPersons.get(p);
//...and so on
I get one complete Person object with the correct gifts. If try to feed the this modified version into a loop, the problem comes back. I've tried using regular for-loops and synchronized collections. I've tried using Google Guava's ImmutableArrayList and still no luck. I know the problem is that I'm changing the lists while accessing them but I can't find anyway around it. I wrote a DAO that uses the MongoDB driver directly and it works properly, but it's a lot more code and quite ugly. I really want this approach to work, the answer is in front of me but I just can't see it. Any help would be greatly appreciated.
Here is your problem:
List<Gift> somePersonsGifts = new ArrayList<Gift>();
....
event.setGifts(somePersonsGifts);
You add the gifts only for one person; if you want to aggregate all the gifts into the event, re-use the existing list.
I don't know anything about MongoDB or Morphia but I suspect the problem is your use of the setters event.setGifts(somePersonsGifts) and person.setEvents(events). Your code does not seem to merge the existing gift and event lists with the ones you are calculating further in the loop, which is how you would want it to behave (if I understand the question correctly).
You should retrieve the allready existing gift list (and event list too) instead of overwriting them with empty new ones.
I don't know if the method merge() is inside the list but I assume that since you are using the list events here
person.setEvents(events);
Maybe you meant
person.setEvents(listOfEvents)
Notice that you are adding all the events to each person. If all the persons went to all the events, it is unnecessary to have the events inside the person.

Categories